blob: 57d9df8e84dc97a2082d5c88701f05250927a62a [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"
Georg Brandlfc8eef32008-03-28 12:11:56 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum5b722181993-03-30 17:46:03 +00008#include "eval.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00009
Guido van Rossum6bf62da1997-04-11 20:37:35 +000010#include <ctype.h>
11
Guido van Rossume2ae77b2001-10-24 20:42:55 +000012#ifdef RISCOS
13#include "unixstuff.h"
14#endif
15
Mark Hammond26cffde2001-05-14 12:17:34 +000016/* The default encoding used by the platform file system APIs
17 Can remain NULL for all platforms that don't have such a concept
18*/
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000019#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Mark Hammond26cffde2001-05-14 12:17:34 +000020const char *Py_FileSystemDefaultEncoding = "mbcs";
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000021#elif defined(__APPLE__)
22const char *Py_FileSystemDefaultEncoding = "utf-8";
Mark Hammond26cffde2001-05-14 12:17:34 +000023#else
24const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
25#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000026
Guido van Rossum12d12c51993-10-26 17:58:25 +000027/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000028static PyObject *filterstring(PyObject *, PyObject *);
Martin v. Löwis8afd7572003-01-25 22:46:11 +000029#ifdef Py_USING_UNICODE
30static PyObject *filterunicode(PyObject *, PyObject *);
31#endif
Tim Petersdbd9ba62000-07-09 03:09:57 +000032static PyObject *filtertuple (PyObject *, PyObject *);
Guido van Rossum12d12c51993-10-26 17:58:25 +000033
Guido van Rossum79f25d91997-04-29 20:08:16 +000034static PyObject *
Neal Norwitz92e212f2006-04-03 04:48:37 +000035builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +000036{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000037 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
38 "level", 0};
39 char *name;
40 PyObject *globals = NULL;
41 PyObject *locals = NULL;
42 PyObject *fromlist = NULL;
43 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +000044
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000045 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
46 kwlist, &name, &globals, &locals, &fromlist, &level))
47 return NULL;
48 return PyImport_ImportModuleLevel(name, globals, locals,
49 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +000050}
51
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000052PyDoc_STRVAR(import_doc,
Neal Norwitz92e212f2006-04-03 04:48:37 +000053"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000054\n\
55Import a module. The globals are only used to determine the context;\n\
56they are not modified. The locals are currently unused. The fromlist\n\
57should be a list of names to emulate ``from name import ...'', or an\n\
58empty list to emulate ``import name''.\n\
59When importing a module from a package, note that __import__('A.B', ...)\n\
60returns package A when fromlist is empty, but its submodule B when\n\
Neal Norwitz92e212f2006-04-03 04:48:37 +000061fromlist is not empty. Level is used to determine whether to perform \n\
62absolute or relative imports. -1 is the original strategy of attempting\n\
63both absolute and relative imports, 0 is absolute, a positive number\n\
64is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000065
Guido van Rossum1ae940a1995-01-02 19:04:15 +000066
Guido van Rossum79f25d91997-04-29 20:08:16 +000067static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000068builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +000069{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000070 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +000071}
72
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000073PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000074"abs(number) -> number\n\
75\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000076Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000077
Raymond Hettinger96229b12005-03-11 06:49:40 +000078static PyObject *
79builtin_all(PyObject *self, PyObject *v)
80{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000081 PyObject *it, *item;
82 PyObject *(*iternext)(PyObject *);
83 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +000084
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000085 it = PyObject_GetIter(v);
86 if (it == NULL)
87 return NULL;
88 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +000089
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000090 for (;;) {
91 item = iternext(it);
92 if (item == NULL)
93 break;
94 cmp = PyObject_IsTrue(item);
95 Py_DECREF(item);
96 if (cmp < 0) {
97 Py_DECREF(it);
98 return NULL;
99 }
100 if (cmp == 0) {
101 Py_DECREF(it);
102 Py_RETURN_FALSE;
103 }
104 }
105 Py_DECREF(it);
106 if (PyErr_Occurred()) {
107 if (PyErr_ExceptionMatches(PyExc_StopIteration))
108 PyErr_Clear();
109 else
110 return NULL;
111 }
112 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000113}
114
115PyDoc_STRVAR(all_doc,
116"all(iterable) -> bool\n\
117\n\
118Return True if bool(x) is True for all values x in the iterable.");
119
120static PyObject *
121builtin_any(PyObject *self, PyObject *v)
122{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000123 PyObject *it, *item;
124 PyObject *(*iternext)(PyObject *);
125 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000126
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000127 it = PyObject_GetIter(v);
128 if (it == NULL)
129 return NULL;
130 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000131
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000132 for (;;) {
133 item = iternext(it);
134 if (item == NULL)
135 break;
136 cmp = PyObject_IsTrue(item);
137 Py_DECREF(item);
138 if (cmp < 0) {
139 Py_DECREF(it);
140 return NULL;
141 }
142 if (cmp == 1) {
143 Py_DECREF(it);
144 Py_RETURN_TRUE;
145 }
146 }
147 Py_DECREF(it);
148 if (PyErr_Occurred()) {
149 if (PyErr_ExceptionMatches(PyExc_StopIteration))
150 PyErr_Clear();
151 else
152 return NULL;
153 }
154 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000155}
156
157PyDoc_STRVAR(any_doc,
158"any(iterable) -> bool\n\
159\n\
160Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000161
Guido van Rossum79f25d91997-04-29 20:08:16 +0000162static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000163builtin_apply(PyObject *self, PyObject *args)
Guido van Rossumc02e15c1991-12-16 13:03:00 +0000164{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000165 PyObject *func, *alist = NULL, *kwdict = NULL;
166 PyObject *t = NULL, *retval = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000167
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000168 if (PyErr_WarnPy3k("apply() not supported in 3.x; "
169 "use func(*args, **kwargs)", 1) < 0)
170 return NULL;
Neal Norwitz8b2bfbc2007-05-23 06:35:32 +0000171
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000172 if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))
173 return NULL;
174 if (alist != NULL) {
175 if (!PyTuple_Check(alist)) {
176 if (!PySequence_Check(alist)) {
177 PyErr_Format(PyExc_TypeError,
178 "apply() arg 2 expected sequence, found %s",
179 alist->ob_type->tp_name);
180 return NULL;
181 }
182 t = PySequence_Tuple(alist);
183 if (t == NULL)
184 return NULL;
185 alist = t;
186 }
187 }
188 if (kwdict != NULL && !PyDict_Check(kwdict)) {
189 PyErr_Format(PyExc_TypeError,
190 "apply() arg 3 expected dictionary, found %s",
191 kwdict->ob_type->tp_name);
192 goto finally;
193 }
194 retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
Barry Warsaw968f8cb1998-10-01 15:33:12 +0000195 finally:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000196 Py_XDECREF(t);
197 return retval;
Guido van Rossumc02e15c1991-12-16 13:03:00 +0000198}
199
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000200PyDoc_STRVAR(apply_doc,
Fred Drakef1fbc622001-01-12 17:05:05 +0000201"apply(object[, args[, kwargs]]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000202\n\
Fred Drake7b912121999-12-23 14:16:55 +0000203Call a callable object with positional arguments taken from the tuple args,\n\
204and keyword arguments taken from the optional dictionary kwargs.\n\
Raymond Hettingerff41c482003-04-06 09:01:11 +0000205Note that classes are callable, as are instances with a __call__() method.\n\
206\n\
207Deprecated since release 2.3. Instead, use the extended call syntax:\n\
208 function(*args, **keywords).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000209
210
Guido van Rossum79f25d91997-04-29 20:08:16 +0000211static PyObject *
Eric Smith3cd81942008-02-22 16:30:22 +0000212builtin_bin(PyObject *self, PyObject *v)
213{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000214 return PyNumber_ToBase(v, 2);
Eric Smith3cd81942008-02-22 16:30:22 +0000215}
216
217PyDoc_STRVAR(bin_doc,
218"bin(number) -> string\n\
219\n\
220Return the binary representation of an integer or long integer.");
221
222
223static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000224builtin_callable(PyObject *self, PyObject *v)
Guido van Rossum2d951851994-08-29 12:52:16 +0000225{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000226 if (PyErr_WarnPy3k("callable() not supported in 3.x; "
227 "use isinstance(x, collections.Callable)", 1) < 0)
228 return NULL;
229 return PyBool_FromLong((long)PyCallable_Check(v));
Guido van Rossum2d951851994-08-29 12:52:16 +0000230}
231
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000232PyDoc_STRVAR(callable_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000233"callable(object) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000234\n\
235Return whether the object is callable (i.e., some kind of function).\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000236Note that classes are callable, as are instances with a __call__() method.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000237
238
Guido van Rossum79f25d91997-04-29 20:08:16 +0000239static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000240builtin_filter(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000241{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000242 PyObject *func, *seq, *result, *it, *arg;
243 Py_ssize_t len; /* guess for result list size */
244 register Py_ssize_t j;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000245
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000246 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
247 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000248
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000249 /* Strings and tuples return a result of the same type. */
250 if (PyString_Check(seq))
251 return filterstring(func, seq);
Martin v. Löwis8afd7572003-01-25 22:46:11 +0000252#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000253 if (PyUnicode_Check(seq))
254 return filterunicode(func, seq);
Martin v. Löwis8afd7572003-01-25 22:46:11 +0000255#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000256 if (PyTuple_Check(seq))
257 return filtertuple(func, seq);
Tim Peters0e57abf2001-05-02 07:39:38 +0000258
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000259 /* Pre-allocate argument list tuple. */
260 arg = PyTuple_New(1);
261 if (arg == NULL)
262 return NULL;
Georg Brandle35b6572005-07-19 22:20:20 +0000263
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000264 /* Get iterator. */
265 it = PyObject_GetIter(seq);
266 if (it == NULL)
267 goto Fail_arg;
Tim Peters0e57abf2001-05-02 07:39:38 +0000268
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000269 /* Guess a result list size. */
270 len = _PyObject_LengthHint(seq, 8);
271 if (len == -1)
272 goto Fail_it;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000273
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000274 /* Get a result list. */
275 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
276 /* Eww - can modify the list in-place. */
277 Py_INCREF(seq);
278 result = seq;
279 }
280 else {
281 result = PyList_New(len);
282 if (result == NULL)
283 goto Fail_it;
284 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000285
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000286 /* Build the result list. */
287 j = 0;
288 for (;;) {
289 PyObject *item;
290 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000291
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000292 item = PyIter_Next(it);
293 if (item == NULL) {
294 if (PyErr_Occurred())
295 goto Fail_result_it;
296 break;
297 }
Guido van Rossumdc4b93d1993-10-27 14:56:44 +0000298
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000299 if (func == (PyObject *)&PyBool_Type || func == Py_None) {
300 ok = PyObject_IsTrue(item);
301 }
302 else {
303 PyObject *good;
304 PyTuple_SET_ITEM(arg, 0, item);
305 good = PyObject_Call(func, arg, NULL);
306 PyTuple_SET_ITEM(arg, 0, NULL);
307 if (good == NULL) {
308 Py_DECREF(item);
309 goto Fail_result_it;
310 }
311 ok = PyObject_IsTrue(good);
312 Py_DECREF(good);
313 }
314 if (ok) {
315 if (j < len)
316 PyList_SET_ITEM(result, j, item);
317 else {
318 int status = PyList_Append(result, item);
319 Py_DECREF(item);
320 if (status < 0)
321 goto Fail_result_it;
322 }
323 ++j;
324 }
325 else
326 Py_DECREF(item);
327 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000328
Guido van Rossum12d12c51993-10-26 17:58:25 +0000329
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000330 /* Cut back result list if len is too big. */
331 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
332 goto Fail_result_it;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000333
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000334 Py_DECREF(it);
335 Py_DECREF(arg);
336 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000337
Tim Peters0e57abf2001-05-02 07:39:38 +0000338Fail_result_it:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000339 Py_DECREF(result);
Tim Peters0e57abf2001-05-02 07:39:38 +0000340Fail_it:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000341 Py_DECREF(it);
Guido van Rossumc7903a12002-08-16 07:04:56 +0000342Fail_arg:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000343 Py_DECREF(arg);
344 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000345}
346
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000347PyDoc_STRVAR(filter_doc,
Tim Petersd50e5442002-03-09 00:06:26 +0000348"filter(function or None, sequence) -> list, tuple, or string\n"
349"\n"
350"Return those items of sequence for which function(item) is true. If\n"
351"function is None, return the items that are true. If sequence is a tuple\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000352"or string, return the same type, else return a list.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000353
Guido van Rossum79f25d91997-04-29 20:08:16 +0000354static PyObject *
Eric Smitha9f7d622008-02-17 19:46:49 +0000355builtin_format(PyObject *self, PyObject *args)
356{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000357 PyObject *value;
358 PyObject *format_spec = NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +0000359
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000360 if (!PyArg_ParseTuple(args, "O|O:format", &value, &format_spec))
361 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +0000362
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000363 return PyObject_Format(value, format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +0000364}
365
366PyDoc_STRVAR(format_doc,
367"format(value[, format_spec]) -> string\n\
368\n\
369Returns value.__format__(format_spec)\n\
370format_spec defaults to \"\"");
371
372static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000373builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000374{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000375 long x;
376 char s[1];
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000377
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000378 if (!PyArg_ParseTuple(args, "l:chr", &x))
379 return NULL;
380 if (x < 0 || x >= 256) {
381 PyErr_SetString(PyExc_ValueError,
382 "chr() arg not in range(256)");
383 return NULL;
384 }
385 s[0] = (char)x;
386 return PyString_FromStringAndSize(s, 1);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000387}
388
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000389PyDoc_STRVAR(chr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000390"chr(i) -> character\n\
391\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000392Return a string of one character with ordinal i; 0 <= i < 256.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000393
394
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000395#ifdef Py_USING_UNICODE
Guido van Rossum79f25d91997-04-29 20:08:16 +0000396static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000397builtin_unichr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000398{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000399 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000400
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000401 if (!PyArg_ParseTuple(args, "i:unichr", &x))
402 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000403
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000404 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000405}
406
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000407PyDoc_STRVAR(unichr_doc,
Fred Drake078b24f2000-04-13 02:42:50 +0000408"unichr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000409\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000410Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000411#endif
Guido van Rossum09095f32000-03-10 23:00:52 +0000412
413
414static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000415builtin_cmp(PyObject *self, PyObject *args)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000416{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000417 PyObject *a, *b;
418 int c;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000419
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000420 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
421 return NULL;
422 if (PyObject_Cmp(a, b, &c) < 0)
423 return NULL;
424 return PyInt_FromLong((long)c);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000425}
426
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000427PyDoc_STRVAR(cmp_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000428"cmp(x, y) -> integer\n\
429\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000430Return negative if x<y, zero if x==y, positive if x>y.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000431
432
Guido van Rossum79f25d91997-04-29 20:08:16 +0000433static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000434builtin_coerce(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000435{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000436 PyObject *v, *w;
437 PyObject *res;
Guido van Rossum5524a591995-01-10 15:26:20 +0000438
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000439 if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
440 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +0000441
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000442 if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
443 return NULL;
444 if (PyNumber_Coerce(&v, &w) < 0)
445 return NULL;
446 res = PyTuple_Pack(2, v, w);
447 Py_DECREF(v);
448 Py_DECREF(w);
449 return res;
Guido van Rossum04691fc1992-08-12 15:35:34 +0000450}
451
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000452PyDoc_STRVAR(coerce_doc,
Martin v. Löwis8d494f32004-08-25 10:42:41 +0000453"coerce(x, y) -> (x1, y1)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000454\n\
Martin v. Löwis8d494f32004-08-25 10:42:41 +0000455Return a tuple consisting of the two numeric arguments converted to\n\
456a common type, using the same rules as used by arithmetic operations.\n\
457If coercion is not possible, raise TypeError.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000458
Guido van Rossum79f25d91997-04-29 20:08:16 +0000459static PyObject *
Georg Brandl5240d742007-03-13 20:46:32 +0000460builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000461{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000462 char *str;
463 char *filename;
464 char *startstr;
465 int mode = -1;
466 int dont_inherit = 0;
467 int supplied_flags = 0;
468 int is_ast;
469 PyCompilerFlags cf;
470 PyObject *result = NULL, *cmd, *tmp = NULL;
471 Py_ssize_t length;
472 static char *kwlist[] = {"source", "filename", "mode", "flags",
473 "dont_inherit", NULL};
474 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000475
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000476 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
477 kwlist, &cmd, &filename, &startstr,
478 &supplied_flags, &dont_inherit))
479 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000480
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000481 cf.cf_flags = supplied_flags;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000482
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000483 if (supplied_flags &
484 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
485 {
486 PyErr_SetString(PyExc_ValueError,
487 "compile(): unrecognised flags");
488 return NULL;
489 }
490 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Georg Brandlfc8eef32008-03-28 12:11:56 +0000491
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000492 if (!dont_inherit) {
493 PyEval_MergeCompilerFlags(&cf);
494 }
Georg Brandlfc8eef32008-03-28 12:11:56 +0000495
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000496 if (strcmp(startstr, "exec") == 0)
497 mode = 0;
498 else if (strcmp(startstr, "eval") == 0)
499 mode = 1;
500 else if (strcmp(startstr, "single") == 0)
501 mode = 2;
502 else {
503 PyErr_SetString(PyExc_ValueError,
504 "compile() arg 3 must be 'exec', 'eval' or 'single'");
505 return NULL;
506 }
Georg Brandlf2bfd542008-03-29 13:24:23 +0000507
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000508 is_ast = PyAST_Check(cmd);
509 if (is_ast == -1)
510 return NULL;
511 if (is_ast) {
512 if (supplied_flags & PyCF_ONLY_AST) {
513 Py_INCREF(cmd);
514 result = cmd;
515 }
516 else {
517 PyArena *arena;
518 mod_ty mod;
Georg Brandlfc8eef32008-03-28 12:11:56 +0000519
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000520 arena = PyArena_New();
521 mod = PyAST_obj2mod(cmd, arena, mode);
522 if (mod == NULL) {
523 PyArena_Free(arena);
524 return NULL;
525 }
526 result = (PyObject*)PyAST_Compile(mod, filename,
527 &cf, arena);
528 PyArena_Free(arena);
529 }
530 return result;
531 }
Georg Brandlfc8eef32008-03-28 12:11:56 +0000532
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000533#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000534 if (PyUnicode_Check(cmd)) {
535 tmp = PyUnicode_AsUTF8String(cmd);
536 if (tmp == NULL)
537 return NULL;
538 cmd = tmp;
539 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
540 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000541#endif
Tim Peters6cd6a822001-08-17 22:11:27 +0000542
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000543 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))
544 goto cleanup;
545 if ((size_t)length != strlen(str)) {
546 PyErr_SetString(PyExc_TypeError,
547 "compile() expected string without null bytes");
548 goto cleanup;
549 }
550 result = Py_CompileStringFlags(str, filename, start[mode], &cf);
Neal Norwitz3a9a3e72005-11-27 20:38:31 +0000551cleanup:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000552 Py_XDECREF(tmp);
553 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000554}
555
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000556PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000557"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000558\n\
559Compile the source string (a Python module, statement or expression)\n\
560into a code object that can be executed by the exec statement or eval().\n\
561The filename will be used for run-time error messages.\n\
562The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000563single (interactive) statement, or 'eval' to compile an expression.\n\
564The flags argument, if present, controls which future statements influence\n\
565the compilation of the code.\n\
566The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
567the effects of any future statements in effect in the code calling\n\
568compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000569in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000570
Guido van Rossum79f25d91997-04-29 20:08:16 +0000571static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000572builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000573{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000574 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000575
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000576 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
577 return NULL;
578 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000579}
580
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000581PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000582"dir([object]) -> list of strings\n"
583"\n"
Georg Brandl871f1bc2007-03-12 13:17:36 +0000584"If called without an argument, return the names in the current scope.\n"
585"Else, return an alphabetized list of names comprising (some of) the attributes\n"
586"of the given object, and of attributes reachable from it.\n"
587"If the object supplies a method named __dir__, it will be used; otherwise\n"
588"the default dir() logic is used and returns:\n"
589" for a module object: the module's attributes.\n"
590" for a class object: its attributes, and recursively the attributes\n"
591" of its bases.\n"
Georg Brandl3bb15672007-03-13 07:23:16 +0000592" for any other object: its attributes, its class's attributes, and\n"
Georg Brandl871f1bc2007-03-12 13:17:36 +0000593" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000594
Guido van Rossum79f25d91997-04-29 20:08:16 +0000595static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000596builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000597{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000598 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000599
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000600 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
601 return NULL;
602 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000603}
604
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000605PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000606"divmod(x, y) -> (div, mod)\n\
607\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000608Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000609
610
Guido van Rossum79f25d91997-04-29 20:08:16 +0000611static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000612builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000613{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000614 PyObject *cmd, *result, *tmp = NULL;
615 PyObject *globals = Py_None, *locals = Py_None;
616 char *str;
617 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000618
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000619 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
620 return NULL;
621 if (locals != Py_None && !PyMapping_Check(locals)) {
622 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
623 return NULL;
624 }
625 if (globals != Py_None && !PyDict_Check(globals)) {
626 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
627 "globals must be a real dict; try eval(expr, {}, mapping)"
628 : "globals must be a dict");
629 return NULL;
630 }
631 if (globals == Py_None) {
632 globals = PyEval_GetGlobals();
633 if (locals == Py_None)
634 locals = PyEval_GetLocals();
635 }
636 else if (locals == Py_None)
637 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000638
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000639 if (globals == NULL || locals == NULL) {
640 PyErr_SetString(PyExc_TypeError,
641 "eval must be given globals and locals "
642 "when called without a frame");
643 return NULL;
644 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000645
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000646 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
647 if (PyDict_SetItemString(globals, "__builtins__",
648 PyEval_GetBuiltins()) != 0)
649 return NULL;
650 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000651
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000652 if (PyCode_Check(cmd)) {
653 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
654 PyErr_SetString(PyExc_TypeError,
655 "code object passed to eval() may not contain free variables");
656 return NULL;
657 }
658 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
659 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000660
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000661 if (!PyString_Check(cmd) &&
662 !PyUnicode_Check(cmd)) {
663 PyErr_SetString(PyExc_TypeError,
664 "eval() arg 1 must be a string or code object");
665 return NULL;
666 }
667 cf.cf_flags = 0;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000668
669#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000670 if (PyUnicode_Check(cmd)) {
671 tmp = PyUnicode_AsUTF8String(cmd);
672 if (tmp == NULL)
673 return NULL;
674 cmd = tmp;
675 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
676 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000677#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000678 if (PyString_AsStringAndSize(cmd, &str, NULL)) {
679 Py_XDECREF(tmp);
680 return NULL;
681 }
682 while (*str == ' ' || *str == '\t')
683 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000684
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000685 (void)PyEval_MergeCompilerFlags(&cf);
686 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
687 Py_XDECREF(tmp);
688 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000689}
690
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000691PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000692"eval(source[, globals[, locals]]) -> value\n\
693\n\
694Evaluate the source in the context of globals and locals.\n\
695The source may be a string representing a Python expression\n\
696or a code object as returned by compile().\n\
Neal Norwitz477ca1c2006-09-05 02:25:41 +0000697The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000698defaulting to the current globals and locals.\n\
699If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000700
701
Guido van Rossum79f25d91997-04-29 20:08:16 +0000702static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000703builtin_execfile(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000704{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000705 char *filename;
706 PyObject *globals = Py_None, *locals = Py_None;
707 PyObject *res;
708 FILE* fp = NULL;
709 PyCompilerFlags cf;
710 int exists;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000711
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000712 if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
713 1) < 0)
714 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +0000715
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000716 if (!PyArg_ParseTuple(args, "s|O!O:execfile",
717 &filename,
718 &PyDict_Type, &globals,
719 &locals))
720 return NULL;
721 if (locals != Py_None && !PyMapping_Check(locals)) {
722 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
723 return NULL;
724 }
725 if (globals == Py_None) {
726 globals = PyEval_GetGlobals();
727 if (locals == Py_None)
728 locals = PyEval_GetLocals();
729 }
730 else if (locals == Py_None)
731 locals = globals;
732 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
733 if (PyDict_SetItemString(globals, "__builtins__",
734 PyEval_GetBuiltins()) != 0)
735 return NULL;
736 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000737
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000738 exists = 0;
739 /* Test for existence or directory. */
Martin v. Löwis3484a182002-03-09 12:07:51 +0000740#if defined(PLAN9)
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000741 {
742 Dir *d;
Martin v. Löwis3484a182002-03-09 12:07:51 +0000743
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000744 if ((d = dirstat(filename))!=nil) {
745 if(d->mode & DMDIR)
746 werrstr("is a directory");
747 else
748 exists = 1;
749 free(d);
750 }
751 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000752#elif defined(RISCOS)
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000753 if (object_exists(filename)) {
754 if (isdir(filename))
755 errno = EISDIR;
756 else
757 exists = 1;
758 }
759#else /* standard Posix */
760 {
761 struct stat s;
762 if (stat(filename, &s) == 0) {
763 if (S_ISDIR(s.st_mode))
764# if defined(PYOS_OS2) && defined(PYCC_VACPP)
765 errno = EOS2ERR;
766# else
767 errno = EISDIR;
768# endif
769 else
770 exists = 1;
771 }
772 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000773#endif
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000774
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000775 if (exists) {
776 Py_BEGIN_ALLOW_THREADS
777 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
778 Py_END_ALLOW_THREADS
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000779
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000780 if (fp == NULL) {
781 exists = 0;
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000782 }
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000783 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000784
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000785 if (!exists) {
786 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
787 return NULL;
788 }
789 cf.cf_flags = 0;
790 if (PyEval_MergeCompilerFlags(&cf))
791 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
792 locals, 1, &cf);
793 else
794 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
795 locals, 1);
796 return res;
Guido van Rossum0f61f8a1992-02-25 18:55:05 +0000797}
798
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000799PyDoc_STRVAR(execfile_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000800"execfile(filename[, globals[, locals]])\n\
801\n\
802Read and execute a Python script from a file.\n\
803The globals and locals are dictionaries, defaulting to the current\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000804globals and locals. If only globals is given, locals defaults to it.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000805
806
Guido van Rossum79f25d91997-04-29 20:08:16 +0000807static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000808builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000809{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000810 PyObject *v, *result, *dflt = NULL;
811 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000812
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000813 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
814 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000815#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000816 if (PyUnicode_Check(name)) {
817 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
818 if (name == NULL)
819 return NULL;
820 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000821#endif
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000822
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000823 if (!PyString_Check(name)) {
824 PyErr_SetString(PyExc_TypeError,
825 "getattr(): attribute name must be string");
826 return NULL;
827 }
828 result = PyObject_GetAttr(v, name);
829 if (result == NULL && dflt != NULL &&
830 PyErr_ExceptionMatches(PyExc_AttributeError))
831 {
832 PyErr_Clear();
833 Py_INCREF(dflt);
834 result = dflt;
835 }
836 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000837}
838
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000839PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000840"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000841\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000842Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
843When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000844exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000845
846
Guido van Rossum79f25d91997-04-29 20:08:16 +0000847static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000848builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000849{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000850 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000851
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000852 d = PyEval_GetGlobals();
853 Py_XINCREF(d);
854 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000855}
856
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000857PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000858"globals() -> dictionary\n\
859\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000860Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000861
862
Guido van Rossum79f25d91997-04-29 20:08:16 +0000863static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000864builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000865{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000866 PyObject *v;
867 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000868
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000869 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
870 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000871#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000872 if (PyUnicode_Check(name)) {
873 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
874 if (name == NULL)
875 return NULL;
876 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000877#endif
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000878
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000879 if (!PyString_Check(name)) {
880 PyErr_SetString(PyExc_TypeError,
881 "hasattr(): attribute name must be string");
882 return NULL;
883 }
884 v = PyObject_GetAttr(v, name);
885 if (v == NULL) {
886 if (!PyErr_ExceptionMatches(PyExc_Exception))
887 return NULL;
888 else {
889 PyErr_Clear();
890 Py_INCREF(Py_False);
891 return Py_False;
892 }
893 }
894 Py_DECREF(v);
895 Py_INCREF(Py_True);
896 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000897}
898
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000899PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000900"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000901\n\
902Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000903(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000904
905
Guido van Rossum79f25d91997-04-29 20:08:16 +0000906static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000907builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000908{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000909 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000910}
911
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000912PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000913"id(object) -> integer\n\
914\n\
915Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000916simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000917
918
Guido van Rossum79f25d91997-04-29 20:08:16 +0000919static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000920builtin_map(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000921{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000922 typedef struct {
923 PyObject *it; /* the iterator object */
924 int saw_StopIteration; /* bool: did the iterator end? */
925 } sequence;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000926
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000927 PyObject *func, *result;
928 sequence *seqs = NULL, *sqp;
929 Py_ssize_t n, len;
930 register int i, j;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000931
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000932 n = PyTuple_Size(args);
933 if (n < 2) {
934 PyErr_SetString(PyExc_TypeError,
935 "map() requires at least two args");
936 return NULL;
937 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000938
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000939 func = PyTuple_GetItem(args, 0);
940 n--;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000941
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000942 if (func == Py_None) {
943 if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
944 "use list(...)", 1) < 0)
945 return NULL;
946 if (n == 1) {
947 /* map(None, S) is the same as list(S). */
948 return PySequence_List(PyTuple_GetItem(args, 1));
949 }
950 }
Guido van Rossumfa4ac711998-07-10 17:37:30 +0000951
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000952 /* Get space for sequence descriptors. Must NULL out the iterator
953 * pointers so that jumping to Fail_2 later doesn't see trash.
954 */
955 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
956 PyErr_NoMemory();
957 return NULL;
958 }
959 for (i = 0; i < n; ++i) {
960 seqs[i].it = (PyObject*)NULL;
961 seqs[i].saw_StopIteration = 0;
962 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000963
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000964 /* Do a first pass to obtain iterators for the arguments, and set len
965 * to the largest of their lengths.
966 */
967 len = 0;
968 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
969 PyObject *curseq;
970 Py_ssize_t curlen;
Guido van Rossumad991772001-01-12 16:03:05 +0000971
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000972 /* Get iterator. */
973 curseq = PyTuple_GetItem(args, i+1);
974 sqp->it = PyObject_GetIter(curseq);
975 if (sqp->it == NULL) {
976 static char errmsg[] =
977 "argument %d to map() must support iteration";
978 char errbuf[sizeof(errmsg) + 25];
979 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
980 PyErr_SetString(PyExc_TypeError, errbuf);
981 goto Fail_2;
982 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000983
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000984 /* Update len. */
985 curlen = _PyObject_LengthHint(curseq, 8);
986 if (curlen > len)
987 len = curlen;
988 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000989
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000990 /* Get space for the result list. */
991 if ((result = (PyObject *) PyList_New(len)) == NULL)
992 goto Fail_2;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000993
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000994 /* Iterate over the sequences until all have stopped. */
995 for (i = 0; ; ++i) {
996 PyObject *alist, *item=NULL, *value;
997 int numactive = 0;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000998
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000999 if (func == Py_None && n == 1)
1000 alist = NULL;
1001 else if ((alist = PyTuple_New(n)) == NULL)
1002 goto Fail_1;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001003
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001004 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
1005 if (sqp->saw_StopIteration) {
1006 Py_INCREF(Py_None);
1007 item = Py_None;
1008 }
1009 else {
1010 item = PyIter_Next(sqp->it);
1011 if (item)
1012 ++numactive;
1013 else {
1014 if (PyErr_Occurred()) {
1015 Py_XDECREF(alist);
1016 goto Fail_1;
1017 }
1018 Py_INCREF(Py_None);
1019 item = Py_None;
1020 sqp->saw_StopIteration = 1;
1021 }
1022 }
1023 if (alist)
1024 PyTuple_SET_ITEM(alist, j, item);
1025 else
1026 break;
1027 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001028
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001029 if (!alist)
1030 alist = item;
Guido van Rossum2d951851994-08-29 12:52:16 +00001031
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001032 if (numactive == 0) {
1033 Py_DECREF(alist);
1034 break;
1035 }
Guido van Rossum2d951851994-08-29 12:52:16 +00001036
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001037 if (func == Py_None)
1038 value = alist;
1039 else {
1040 value = PyEval_CallObject(func, alist);
1041 Py_DECREF(alist);
1042 if (value == NULL)
1043 goto Fail_1;
1044 }
1045 if (i >= len) {
1046 int status = PyList_Append(result, value);
1047 Py_DECREF(value);
1048 if (status < 0)
1049 goto Fail_1;
1050 }
1051 else if (PyList_SetItem(result, i, value) < 0)
1052 goto Fail_1;
1053 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001054
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001055 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
1056 goto Fail_1;
Guido van Rossumfa4ac711998-07-10 17:37:30 +00001057
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001058 goto Succeed;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001059
Guido van Rossum12d12c51993-10-26 17:58:25 +00001060Fail_1:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001061 Py_DECREF(result);
Guido van Rossum12d12c51993-10-26 17:58:25 +00001062Fail_2:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001063 result = NULL;
Tim Peters4e9afdc2001-05-03 23:54:49 +00001064Succeed:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001065 assert(seqs);
1066 for (i = 0; i < n; ++i)
1067 Py_XDECREF(seqs[i].it);
1068 PyMem_DEL(seqs);
1069 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001070}
1071
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001072PyDoc_STRVAR(map_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001073"map(function, sequence[, sequence, ...]) -> list\n\
1074\n\
1075Return a list of the results of applying the function to the items of\n\
1076the argument sequence(s). If more than one sequence is given, the\n\
1077function is called with an argument list consisting of the corresponding\n\
1078item of each sequence, substituting None for missing values when not all\n\
1079sequences have the same length. If the function is None, return a list of\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001080the items of the sequence (or a list of tuples if more than one sequence).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001081
1082
Guido van Rossum79f25d91997-04-29 20:08:16 +00001083static PyObject *
Georg Brandl28e08732008-04-30 19:47:09 +00001084builtin_next(PyObject *self, PyObject *args)
1085{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001086 PyObject *it, *res;
1087 PyObject *def = NULL;
Georg Brandl28e08732008-04-30 19:47:09 +00001088
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001089 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1090 return NULL;
1091 if (!PyIter_Check(it)) {
1092 PyErr_Format(PyExc_TypeError,
1093 "%.200s object is not an iterator",
1094 it->ob_type->tp_name);
1095 return NULL;
1096 }
1097
1098 res = (*it->ob_type->tp_iternext)(it);
1099 if (res != NULL) {
1100 return res;
1101 } else if (def != NULL) {
1102 if (PyErr_Occurred()) {
1103 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
1104 return NULL;
1105 PyErr_Clear();
1106 }
1107 Py_INCREF(def);
1108 return def;
1109 } else if (PyErr_Occurred()) {
1110 return NULL;
1111 } else {
1112 PyErr_SetNone(PyExc_StopIteration);
1113 return NULL;
1114 }
Georg Brandl28e08732008-04-30 19:47:09 +00001115}
1116
1117PyDoc_STRVAR(next_doc,
1118"next(iterator[, default])\n\
1119\n\
1120Return the next item from the iterator. If default is given and the iterator\n\
1121is exhausted, it is returned instead of raising StopIteration.");
1122
1123
1124static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001125builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001126{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001127 PyObject *v;
1128 PyObject *name;
1129 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001130
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001131 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1132 return NULL;
1133 if (PyObject_SetAttr(v, name, value) != 0)
1134 return NULL;
1135 Py_INCREF(Py_None);
1136 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001137}
1138
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001139PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001140"setattr(object, name, value)\n\
1141\n\
1142Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001143``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001144
1145
Guido van Rossum79f25d91997-04-29 20:08:16 +00001146static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001147builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001148{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001149 PyObject *v;
1150 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001151
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001152 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1153 return NULL;
1154 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1155 return NULL;
1156 Py_INCREF(Py_None);
1157 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001158}
1159
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001160PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001161"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001162\n\
1163Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001164``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001165
1166
Guido van Rossum79f25d91997-04-29 20:08:16 +00001167static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001168builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001169{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001170 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001171
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001172 x = PyObject_Hash(v);
1173 if (x == -1)
1174 return NULL;
1175 return PyInt_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001176}
1177
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001178PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001179"hash(object) -> integer\n\
1180\n\
1181Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001182the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001183
1184
Guido van Rossum79f25d91997-04-29 20:08:16 +00001185static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001186builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001187{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001188 PyNumberMethods *nb;
1189 PyObject *res;
Benjamin Petersonc6d64ec2008-05-17 20:09:42 +00001190
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001191 if ((nb = v->ob_type->tp_as_number) == NULL ||
1192 nb->nb_hex == NULL) {
1193 PyErr_SetString(PyExc_TypeError,
1194 "hex() argument can't be converted to hex");
1195 return NULL;
1196 }
1197 res = (*nb->nb_hex)(v);
1198 if (res && !PyString_Check(res)) {
1199 PyErr_Format(PyExc_TypeError,
1200 "__hex__ returned non-string (type %.200s)",
1201 res->ob_type->tp_name);
1202 Py_DECREF(res);
1203 return NULL;
1204 }
1205 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001206}
1207
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001208PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001209"hex(number) -> string\n\
1210\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001211Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001212
1213
Tim Petersdbd9ba62000-07-09 03:09:57 +00001214static PyObject *builtin_raw_input(PyObject *, PyObject *);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001215
Guido van Rossum79f25d91997-04-29 20:08:16 +00001216static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001217builtin_input(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001218{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001219 PyObject *line;
1220 char *str;
1221 PyObject *res;
1222 PyObject *globals, *locals;
1223 PyCompilerFlags cf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001224
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001225 line = builtin_raw_input(self, args);
1226 if (line == NULL)
1227 return line;
1228 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1229 return NULL;
1230 while (*str == ' ' || *str == '\t')
1231 str++;
1232 globals = PyEval_GetGlobals();
1233 locals = PyEval_GetLocals();
1234 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1235 if (PyDict_SetItemString(globals, "__builtins__",
1236 PyEval_GetBuiltins()) != 0)
1237 return NULL;
1238 }
1239 cf.cf_flags = 0;
1240 PyEval_MergeCompilerFlags(&cf);
1241 res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1242 Py_DECREF(line);
1243 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001244}
1245
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001246PyDoc_STRVAR(input_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001247"input([prompt]) -> value\n\
1248\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001249Equivalent to eval(raw_input(prompt)).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001250
1251
Guido van Rossume8811f81997-02-14 15:48:05 +00001252static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001253builtin_intern(PyObject *self, PyObject *args)
Guido van Rossume8811f81997-02-14 15:48:05 +00001254{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001255 PyObject *s;
1256 if (!PyArg_ParseTuple(args, "S:intern", &s))
1257 return NULL;
1258 if (!PyString_CheckExact(s)) {
1259 PyErr_SetString(PyExc_TypeError,
1260 "can't intern subclass of string");
1261 return NULL;
1262 }
1263 Py_INCREF(s);
1264 PyString_InternInPlace(&s);
1265 return s;
Guido van Rossume8811f81997-02-14 15:48:05 +00001266}
1267
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001268PyDoc_STRVAR(intern_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001269"intern(string) -> string\n\
1270\n\
1271``Intern'' the given string. This enters the string in the (global)\n\
1272table of interned strings whose purpose is to speed up dictionary lookups.\n\
1273Return the string itself or the previously interned string object with the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001274same value.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001275
1276
Guido van Rossum79f25d91997-04-29 20:08:16 +00001277static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001278builtin_iter(PyObject *self, PyObject *args)
1279{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001280 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001281
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001282 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1283 return NULL;
1284 if (w == NULL)
1285 return PyObject_GetIter(v);
1286 if (!PyCallable_Check(v)) {
1287 PyErr_SetString(PyExc_TypeError,
1288 "iter(v, w): v must be callable");
1289 return NULL;
1290 }
1291 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001292}
1293
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001294PyDoc_STRVAR(iter_doc,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001295"iter(collection) -> iterator\n\
1296iter(callable, sentinel) -> iterator\n\
1297\n\
1298Get an iterator from an object. In the first form, the argument must\n\
1299supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001300In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001301
1302
1303static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001304builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001305{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001306 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001307
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001308 res = PyObject_Size(v);
1309 if (res < 0 && PyErr_Occurred())
1310 return NULL;
1311 return PyInt_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001312}
1313
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001314PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001315"len(object) -> integer\n\
1316\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001317Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001318
1319
Guido van Rossum79f25d91997-04-29 20:08:16 +00001320static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001321builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001322{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001323 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001324
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001325 d = PyEval_GetLocals();
1326 Py_XINCREF(d);
1327 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001328}
1329
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001330PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001331"locals() -> dictionary\n\
1332\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001333Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001334
1335
Guido van Rossum79f25d91997-04-29 20:08:16 +00001336static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001337min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001338{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001339 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1340 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001341
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001342 if (PyTuple_Size(args) > 1)
1343 v = args;
1344 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1345 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001346
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001347 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1348 keyfunc = PyDict_GetItemString(kwds, "key");
1349 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1350 PyErr_Format(PyExc_TypeError,
1351 "%s() got an unexpected keyword argument", name);
1352 return NULL;
1353 }
1354 Py_INCREF(keyfunc);
1355 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001356
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001357 it = PyObject_GetIter(v);
1358 if (it == NULL) {
1359 Py_XDECREF(keyfunc);
1360 return NULL;
1361 }
Tim Petersc3074532001-05-03 07:00:32 +00001362
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001363 maxitem = NULL; /* the result */
1364 maxval = NULL; /* the value associated with the result */
1365 while (( item = PyIter_Next(it) )) {
1366 /* get the value from the key function */
1367 if (keyfunc != NULL) {
1368 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1369 if (val == NULL)
1370 goto Fail_it_item;
1371 }
1372 /* no key function; the value is the item */
1373 else {
1374 val = item;
1375 Py_INCREF(val);
1376 }
Tim Petersc3074532001-05-03 07:00:32 +00001377
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001378 /* maximum value and item are unset; set them */
1379 if (maxval == NULL) {
1380 maxitem = item;
1381 maxval = val;
1382 }
1383 /* maximum value and item are set; update them as necessary */
1384 else {
1385 int cmp = PyObject_RichCompareBool(val, maxval, op);
1386 if (cmp < 0)
1387 goto Fail_it_item_and_val;
1388 else if (cmp > 0) {
1389 Py_DECREF(maxval);
1390 Py_DECREF(maxitem);
1391 maxval = val;
1392 maxitem = item;
1393 }
1394 else {
1395 Py_DECREF(item);
1396 Py_DECREF(val);
1397 }
1398 }
1399 }
1400 if (PyErr_Occurred())
1401 goto Fail_it;
1402 if (maxval == NULL) {
1403 PyErr_Format(PyExc_ValueError,
1404 "%s() arg is an empty sequence", name);
1405 assert(maxitem == NULL);
1406 }
1407 else
1408 Py_DECREF(maxval);
1409 Py_DECREF(it);
1410 Py_XDECREF(keyfunc);
1411 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001412
1413Fail_it_item_and_val:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001414 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001415Fail_it_item:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001416 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001417Fail_it:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001418 Py_XDECREF(maxval);
1419 Py_XDECREF(maxitem);
1420 Py_DECREF(it);
1421 Py_XDECREF(keyfunc);
1422 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001423}
1424
Guido van Rossum79f25d91997-04-29 20:08:16 +00001425static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001426builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001427{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001428 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001429}
1430
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001431PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001432"min(iterable[, key=func]) -> value\n\
1433min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001434\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001435With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001436With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001437
1438
Guido van Rossum79f25d91997-04-29 20:08:16 +00001439static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001440builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001441{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001442 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001443}
1444
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001445PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001446"max(iterable[, key=func]) -> value\n\
1447max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001448\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001449With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001450With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001451
1452
Guido van Rossum79f25d91997-04-29 20:08:16 +00001453static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001454builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001455{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001456 PyNumberMethods *nb;
1457 PyObject *res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001458
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001459 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1460 nb->nb_oct == NULL) {
1461 PyErr_SetString(PyExc_TypeError,
1462 "oct() argument can't be converted to oct");
1463 return NULL;
1464 }
1465 res = (*nb->nb_oct)(v);
1466 if (res && !PyString_Check(res)) {
1467 PyErr_Format(PyExc_TypeError,
1468 "__oct__ returned non-string (type %.200s)",
1469 res->ob_type->tp_name);
1470 Py_DECREF(res);
1471 return NULL;
1472 }
1473 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001474}
1475
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001476PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001477"oct(number) -> string\n\
1478\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001479Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001480
1481
Guido van Rossum79f25d91997-04-29 20:08:16 +00001482static PyObject *
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001483builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
1484{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001485 return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001486}
1487
1488PyDoc_STRVAR(open_doc,
1489"open(name[, mode[, buffering]]) -> file object\n\
1490\n\
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00001491Open a file using the file() type, returns a file object. This is the\n\
1492preferred way to open a file.");
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001493
1494
1495static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001496builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001497{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001498 long ord;
1499 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001500
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001501 if (PyString_Check(obj)) {
1502 size = PyString_GET_SIZE(obj);
1503 if (size == 1) {
1504 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1505 return PyInt_FromLong(ord);
1506 }
1507 } else if (PyByteArray_Check(obj)) {
1508 size = PyByteArray_GET_SIZE(obj);
1509 if (size == 1) {
1510 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1511 return PyInt_FromLong(ord);
1512 }
Christian Heimes1a6387e2008-03-26 12:49:49 +00001513
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001514#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001515 } else if (PyUnicode_Check(obj)) {
1516 size = PyUnicode_GET_SIZE(obj);
1517 if (size == 1) {
1518 ord = (long)*PyUnicode_AS_UNICODE(obj);
1519 return PyInt_FromLong(ord);
1520 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001521#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001522 } else {
1523 PyErr_Format(PyExc_TypeError,
1524 "ord() expected string of length 1, but " \
1525 "%.200s found", obj->ob_type->tp_name);
1526 return NULL;
1527 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001528
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001529 PyErr_Format(PyExc_TypeError,
1530 "ord() expected a character, "
1531 "but string of length %zd found",
1532 size);
1533 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001534}
1535
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001536PyDoc_STRVAR(ord_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001537"ord(c) -> integer\n\
1538\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001539Return the integer ordinal of a one-character string.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001540
1541
Guido van Rossum79f25d91997-04-29 20:08:16 +00001542static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001543builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001544{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001545 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001546
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001547 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1548 return NULL;
1549 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001550}
1551
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001552PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001553"pow(x, y[, z]) -> number\n\
1554\n\
1555With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001556equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001557
1558
Eric Smith7c478942008-03-18 23:45:49 +00001559static PyObject *
1560builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1561{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001562 static char *kwlist[] = {"sep", "end", "file", 0};
1563 static PyObject *dummy_args = NULL;
1564 static PyObject *unicode_newline = NULL, *unicode_space = NULL;
1565 static PyObject *str_newline = NULL, *str_space = NULL;
1566 PyObject *newline, *space;
1567 PyObject *sep = NULL, *end = NULL, *file = NULL;
1568 int i, err, use_unicode = 0;
Eric Smith7c478942008-03-18 23:45:49 +00001569
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001570 if (dummy_args == NULL) {
1571 if (!(dummy_args = PyTuple_New(0)))
1572 return NULL;
1573 }
1574 if (str_newline == NULL) {
1575 str_newline = PyString_FromString("\n");
1576 if (str_newline == NULL)
1577 return NULL;
1578 str_space = PyString_FromString(" ");
1579 if (str_space == NULL) {
1580 Py_CLEAR(str_newline);
1581 return NULL;
1582 }
1583 unicode_newline = PyUnicode_FromString("\n");
1584 if (unicode_newline == NULL) {
1585 Py_CLEAR(str_newline);
1586 Py_CLEAR(str_space);
1587 return NULL;
1588 }
1589 unicode_space = PyUnicode_FromString(" ");
1590 if (unicode_space == NULL) {
1591 Py_CLEAR(str_newline);
1592 Py_CLEAR(str_space);
1593 Py_CLEAR(unicode_space);
1594 return NULL;
1595 }
1596 }
1597 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1598 kwlist, &sep, &end, &file))
1599 return NULL;
1600 if (file == NULL || file == Py_None) {
1601 file = PySys_GetObject("stdout");
1602 /* sys.stdout may be None when FILE* stdout isn't connected */
1603 if (file == Py_None)
1604 Py_RETURN_NONE;
1605 }
1606 if (sep == Py_None) {
1607 sep = NULL;
1608 }
1609 else if (sep) {
1610 if (PyUnicode_Check(sep)) {
1611 use_unicode = 1;
1612 }
1613 else if (!PyString_Check(sep)) {
1614 PyErr_Format(PyExc_TypeError,
1615 "sep must be None, str or unicode, not %.200s",
1616 sep->ob_type->tp_name);
1617 return NULL;
1618 }
1619 }
1620 if (end == Py_None)
1621 end = NULL;
1622 else if (end) {
1623 if (PyUnicode_Check(end)) {
1624 use_unicode = 1;
1625 }
1626 else if (!PyString_Check(end)) {
1627 PyErr_Format(PyExc_TypeError,
1628 "end must be None, str or unicode, not %.200s",
1629 end->ob_type->tp_name);
1630 return NULL;
1631 }
1632 }
Benjamin Peterson7d6b0142009-07-02 18:19:47 +00001633
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001634 if (!use_unicode) {
1635 for (i = 0; i < PyTuple_Size(args); i++) {
1636 if (PyUnicode_Check(PyTuple_GET_ITEM(args, i))) {
1637 use_unicode = 1;
1638 break;
1639 }
1640 }
1641 }
1642 if (use_unicode) {
1643 newline = unicode_newline;
1644 space = unicode_space;
1645 }
1646 else {
1647 newline = str_newline;
1648 space = str_space;
1649 }
Eric Smith7c478942008-03-18 23:45:49 +00001650
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001651 for (i = 0; i < PyTuple_Size(args); i++) {
1652 if (i > 0) {
1653 if (sep == NULL)
1654 err = PyFile_WriteObject(space, file,
1655 Py_PRINT_RAW);
1656 else
1657 err = PyFile_WriteObject(sep, file,
1658 Py_PRINT_RAW);
1659 if (err)
1660 return NULL;
1661 }
1662 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1663 Py_PRINT_RAW);
1664 if (err)
1665 return NULL;
1666 }
Eric Smith7c478942008-03-18 23:45:49 +00001667
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001668 if (end == NULL)
1669 err = PyFile_WriteObject(newline, file, Py_PRINT_RAW);
1670 else
1671 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1672 if (err)
1673 return NULL;
Eric Smith7c478942008-03-18 23:45:49 +00001674
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001675 Py_RETURN_NONE;
Eric Smith7c478942008-03-18 23:45:49 +00001676}
1677
1678PyDoc_STRVAR(print_doc,
1679"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
1680\n\
1681Prints the values to a stream, or to sys.stdout by default.\n\
1682Optional keyword arguments:\n\
1683file: a file-like object (stream); defaults to the current sys.stdout.\n\
1684sep: string inserted between values, default a space.\n\
1685end: string appended after the last value, default a newline.");
1686
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001687
1688/* Return number of items in range (lo, hi, step), when arguments are
1689 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1690 * & only if the true value is too large to fit in a signed long.
1691 * Arguments MUST return 1 with either PyInt_Check() or
1692 * PyLong_Check(). Return -1 when there is an error.
1693 */
1694static long
1695get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
1696{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001697 /* -------------------------------------------------------------
1698 Algorithm is equal to that of get_len_of_range(), but it operates
1699 on PyObjects (which are assumed to be PyLong or PyInt objects).
1700 ---------------------------------------------------------------*/
1701 long n;
1702 PyObject *diff = NULL;
1703 PyObject *one = NULL;
1704 PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
1705 /* holds sub-expression evaluations */
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001706
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001707 /* if (lo >= hi), return length of 0. */
1708 if (PyObject_Compare(lo, hi) >= 0)
1709 return 0;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001710
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001711 if ((one = PyLong_FromLong(1L)) == NULL)
1712 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001713
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001714 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
1715 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001716
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001717 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
1718 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001719
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001720 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
1721 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001722
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001723 if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
1724 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001725
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001726 n = PyLong_AsLong(tmp3);
1727 if (PyErr_Occurred()) { /* Check for Overflow */
1728 PyErr_Clear();
1729 goto Fail;
1730 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001731
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001732 Py_DECREF(tmp3);
1733 Py_DECREF(tmp2);
1734 Py_DECREF(diff);
1735 Py_DECREF(tmp1);
1736 Py_DECREF(one);
1737 return n;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001738
1739 Fail:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001740 Py_XDECREF(tmp3);
1741 Py_XDECREF(tmp2);
1742 Py_XDECREF(diff);
1743 Py_XDECREF(tmp1);
1744 Py_XDECREF(one);
1745 return -1;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001746}
1747
Mark Dickinsone02c9d22010-05-07 13:23:18 +00001748/* Helper function for handle_range_longs. If arg is int or long
1749 object, returns it with incremented reference count. If arg is
1750 float, raises type error. As a last resort, creates a new int by
1751 calling arg type's nb_int method if it is defined. Returns NULL
1752 and sets exception on error.
1753
1754 Returns a new reference to an int object. */
1755static PyObject *
1756get_range_long_argument(PyObject *arg, const char *name)
1757{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001758 PyObject *v;
1759 PyNumberMethods *nb;
1760 if (PyInt_Check(arg) || PyLong_Check(arg)) {
1761 Py_INCREF(arg);
1762 return arg;
1763 }
1764 if (PyFloat_Check(arg) ||
1765 (nb = Py_TYPE(arg)->tp_as_number) == NULL ||
1766 nb->nb_int == NULL) {
1767 PyErr_Format(PyExc_TypeError,
1768 "range() integer %s argument expected, got %s.",
1769 name, arg->ob_type->tp_name);
1770 return NULL;
1771 }
1772 v = nb->nb_int(arg);
1773 if (v == NULL)
1774 return NULL;
1775 if (PyInt_Check(v) || PyLong_Check(v))
1776 return v;
1777 Py_DECREF(v);
1778 PyErr_SetString(PyExc_TypeError,
1779 "__int__ should return int object");
1780 return NULL;
Mark Dickinsone02c9d22010-05-07 13:23:18 +00001781}
1782
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001783/* An extension of builtin_range() that handles the case when PyLong
1784 * arguments are given. */
1785static PyObject *
1786handle_range_longs(PyObject *self, PyObject *args)
1787{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001788 PyObject *ilow = NULL;
1789 PyObject *ihigh = NULL;
1790 PyObject *istep = NULL;
Tim Peters874e1f72003-04-13 22:13:08 +00001791
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001792 PyObject *low = NULL;
1793 PyObject *high = NULL;
1794 PyObject *step = NULL;
Mark Dickinsone02c9d22010-05-07 13:23:18 +00001795
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001796 PyObject *curnum = NULL;
1797 PyObject *v = NULL;
1798 long bign;
1799 int i, n;
1800 int cmp_result;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001801
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001802 PyObject *zero = PyLong_FromLong(0);
Tim Peters874e1f72003-04-13 22:13:08 +00001803
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001804 if (zero == NULL)
1805 return NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001806
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001807 if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
1808 Py_DECREF(zero);
1809 return NULL;
1810 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001811
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001812 /* Figure out which way we were called, supply defaults, and be
1813 * sure to incref everything so that the decrefs at the end
1814 * are correct. NB: ilow, ihigh and istep are borrowed references.
1815 */
1816 assert(ilow != NULL);
1817 if (ihigh == NULL) {
1818 /* only 1 arg -- it's the upper limit */
1819 ihigh = ilow;
1820 ilow = NULL;
1821 }
Mark Dickinsone02c9d22010-05-07 13:23:18 +00001822
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001823 /* convert ihigh if necessary */
1824 assert(ihigh != NULL);
1825 high = get_range_long_argument(ihigh, "end");
1826 if (high == NULL)
1827 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001828
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001829 /* ihigh correct now; do ilow */
1830 if (ilow == NULL) {
1831 Py_INCREF(zero);
1832 low = zero;
1833 }
1834 else {
1835 low = get_range_long_argument(ilow, "start");
1836 if (low == NULL)
1837 goto Fail;
1838 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001839
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001840 /* ilow and ihigh correct now; do istep */
1841 if (istep == NULL)
1842 step = PyLong_FromLong(1);
1843 else
1844 step = get_range_long_argument(istep, "step");
1845 if (step == NULL)
1846 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001847
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001848 if (PyObject_Cmp(step, zero, &cmp_result) == -1)
1849 goto Fail;
Tim Peters874e1f72003-04-13 22:13:08 +00001850
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001851 if (cmp_result == 0) {
1852 PyErr_SetString(PyExc_ValueError,
1853 "range() step argument must not be zero");
1854 goto Fail;
1855 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001856
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001857 if (cmp_result > 0)
1858 bign = get_len_of_range_longs(low, high, step);
1859 else {
1860 PyObject *neg_step = PyNumber_Negative(step);
1861 if (neg_step == NULL)
1862 goto Fail;
1863 bign = get_len_of_range_longs(high, low, neg_step);
1864 Py_DECREF(neg_step);
1865 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001866
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001867 n = (int)bign;
1868 if (bign < 0 || (long)n != bign) {
1869 PyErr_SetString(PyExc_OverflowError,
1870 "range() result has too many items");
1871 goto Fail;
1872 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001873
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001874 v = PyList_New(n);
1875 if (v == NULL)
1876 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001877
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001878 curnum = low;
1879 Py_INCREF(curnum);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001880
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001881 for (i = 0; i < n; i++) {
1882 PyObject *w = PyNumber_Long(curnum);
1883 PyObject *tmp_num;
1884 if (w == NULL)
1885 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001886
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001887 PyList_SET_ITEM(v, i, w);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001888
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001889 tmp_num = PyNumber_Add(curnum, step);
1890 if (tmp_num == NULL)
1891 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001892
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001893 Py_DECREF(curnum);
1894 curnum = tmp_num;
1895 }
1896 Py_DECREF(low);
1897 Py_DECREF(high);
1898 Py_DECREF(step);
1899 Py_DECREF(zero);
1900 Py_DECREF(curnum);
1901 return v;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001902
1903 Fail:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001904 Py_XDECREF(low);
1905 Py_XDECREF(high);
1906 Py_XDECREF(step);
1907 Py_DECREF(zero);
1908 Py_XDECREF(curnum);
1909 Py_XDECREF(v);
1910 return NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001911}
1912
Guido van Rossum124eff01999-02-23 16:11:01 +00001913/* Return number of items in range/xrange (lo, hi, step). step > 0
1914 * required. Return a value < 0 if & only if the true value is too
1915 * large to fit in a signed long.
1916 */
1917static long
Thomas Wouterse28c2962000-07-23 22:21:32 +00001918get_len_of_range(long lo, long hi, long step)
Guido van Rossum124eff01999-02-23 16:11:01 +00001919{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001920 /* -------------------------------------------------------------
1921 If lo >= hi, the range is empty.
1922 Else if n values are in the range, the last one is
1923 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1924 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1925 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1926 the RHS is non-negative and so truncation is the same as the
1927 floor. Letting M be the largest positive long, the worst case
1928 for the RHS numerator is hi=M, lo=-M-1, and then
1929 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1930 precision to compute the RHS exactly.
1931 ---------------------------------------------------------------*/
1932 long n = 0;
1933 if (lo < hi) {
1934 unsigned long uhi = (unsigned long)hi;
1935 unsigned long ulo = (unsigned long)lo;
1936 unsigned long diff = uhi - ulo - 1;
1937 n = (long)(diff / (unsigned long)step + 1);
1938 }
1939 return n;
Guido van Rossum124eff01999-02-23 16:11:01 +00001940}
1941
Guido van Rossum79f25d91997-04-29 20:08:16 +00001942static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001943builtin_range(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001944{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001945 long ilow = 0, ihigh = 0, istep = 1;
1946 long bign;
1947 int i, n;
Guido van Rossum124eff01999-02-23 16:11:01 +00001948
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001949 PyObject *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001950
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001951 if (PyTuple_Size(args) <= 1) {
1952 if (!PyArg_ParseTuple(args,
1953 "l;range() requires 1-3 int arguments",
1954 &ihigh)) {
1955 PyErr_Clear();
1956 return handle_range_longs(self, args);
1957 }
1958 }
1959 else {
1960 if (!PyArg_ParseTuple(args,
1961 "ll|l;range() requires 1-3 int arguments",
1962 &ilow, &ihigh, &istep)) {
1963 PyErr_Clear();
1964 return handle_range_longs(self, args);
1965 }
1966 }
1967 if (istep == 0) {
1968 PyErr_SetString(PyExc_ValueError,
1969 "range() step argument must not be zero");
1970 return NULL;
1971 }
1972 if (istep > 0)
1973 bign = get_len_of_range(ilow, ihigh, istep);
1974 else
1975 bign = get_len_of_range(ihigh, ilow, -istep);
1976 n = (int)bign;
1977 if (bign < 0 || (long)n != bign) {
1978 PyErr_SetString(PyExc_OverflowError,
1979 "range() result has too many items");
1980 return NULL;
1981 }
1982 v = PyList_New(n);
1983 if (v == NULL)
1984 return NULL;
1985 for (i = 0; i < n; i++) {
1986 PyObject *w = PyInt_FromLong(ilow);
1987 if (w == NULL) {
1988 Py_DECREF(v);
1989 return NULL;
1990 }
1991 PyList_SET_ITEM(v, i, w);
1992 ilow += istep;
1993 }
1994 return v;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001995}
1996
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001997PyDoc_STRVAR(range_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001998"range([start,] stop[, step]) -> list of integers\n\
1999\n\
2000Return a list containing an arithmetic progression of integers.\n\
2001range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
2002When step is given, it specifies the increment (or decrement).\n\
2003For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002004These are exactly the valid indices for a list of 4 elements.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002005
2006
Guido van Rossum79f25d91997-04-29 20:08:16 +00002007static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002008builtin_raw_input(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002009{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002010 PyObject *v = NULL;
2011 PyObject *fin = PySys_GetObject("stdin");
2012 PyObject *fout = PySys_GetObject("stdout");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002013
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002014 if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
2015 return NULL;
Martin v. Löwis31d2df52002-08-14 15:46:02 +00002016
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002017 if (fin == NULL) {
2018 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
2019 return NULL;
2020 }
2021 if (fout == NULL) {
2022 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
2023 return NULL;
2024 }
2025 if (PyFile_SoftSpace(fout, 0)) {
2026 if (PyFile_WriteString(" ", fout) != 0)
2027 return NULL;
2028 }
2029 if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
2030 && isatty(fileno(PyFile_AsFile(fin)))
2031 && isatty(fileno(PyFile_AsFile(fout)))) {
2032 PyObject *po;
2033 char *prompt;
2034 char *s;
2035 PyObject *result;
2036 if (v != NULL) {
2037 po = PyObject_Str(v);
2038 if (po == NULL)
2039 return NULL;
2040 prompt = PyString_AsString(po);
2041 if (prompt == NULL)
2042 return NULL;
2043 }
2044 else {
2045 po = NULL;
2046 prompt = "";
2047 }
2048 s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
2049 prompt);
2050 Py_XDECREF(po);
2051 if (s == NULL) {
2052 if (!PyErr_Occurred())
2053 PyErr_SetNone(PyExc_KeyboardInterrupt);
2054 return NULL;
2055 }
2056 if (*s == '\0') {
2057 PyErr_SetNone(PyExc_EOFError);
2058 result = NULL;
2059 }
2060 else { /* strip trailing '\n' */
2061 size_t len = strlen(s);
2062 if (len > PY_SSIZE_T_MAX) {
2063 PyErr_SetString(PyExc_OverflowError,
2064 "[raw_]input: input too long");
2065 result = NULL;
2066 }
2067 else {
2068 result = PyString_FromStringAndSize(s, len-1);
2069 }
2070 }
2071 PyMem_FREE(s);
2072 return result;
2073 }
2074 if (v != NULL) {
2075 if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
2076 return NULL;
2077 }
2078 return PyFile_GetLine(fin, -1);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002079}
2080
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002081PyDoc_STRVAR(raw_input_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002082"raw_input([prompt]) -> string\n\
2083\n\
2084Read a string from standard input. The trailing newline is stripped.\n\
2085If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
2086On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002087is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002088
2089
Guido van Rossum79f25d91997-04-29 20:08:16 +00002090static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002091builtin_reduce(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002092{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002093 static PyObject *functools_reduce = NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002094
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002095 if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
2096 "use functools.reduce()", 1) < 0)
2097 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +00002098
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002099 if (functools_reduce == NULL) {
2100 PyObject *functools = PyImport_ImportModule("functools");
2101 if (functools == NULL)
2102 return NULL;
2103 functools_reduce = PyObject_GetAttrString(functools, "reduce");
2104 Py_DECREF(functools);
2105 if (functools_reduce == NULL)
2106 return NULL;
2107 }
2108 return PyObject_Call(functools_reduce, args, NULL);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002109}
2110
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002111PyDoc_STRVAR(reduce_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002112"reduce(function, sequence[, initial]) -> value\n\
2113\n\
2114Apply a function of two arguments cumulatively to the items of a sequence,\n\
2115from left to right, so as to reduce the sequence to a single value.\n\
2116For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
2117((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
2118of the sequence in the calculation, and serves as a default when the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002119sequence is empty.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002120
2121
Guido van Rossum79f25d91997-04-29 20:08:16 +00002122static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002123builtin_reload(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002124{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002125 if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
2126 1) < 0)
2127 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +00002128
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002129 return PyImport_ReloadModule(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002130}
2131
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002132PyDoc_STRVAR(reload_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002133"reload(module) -> module\n\
2134\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002135Reload the module. The module must have been successfully imported before.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002136
2137
Guido van Rossum79f25d91997-04-29 20:08:16 +00002138static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002139builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00002140{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002141 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002142}
2143
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002144PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002145"repr(object) -> string\n\
2146\n\
2147Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002148For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002149
2150
Guido van Rossum79f25d91997-04-29 20:08:16 +00002151static PyObject *
Georg Brandlccadf842006-03-31 18:54:53 +00002152builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002153{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002154 double number, abs_number, abs_result;
2155 double f;
2156 int ndigits = 0;
2157 int i;
2158 static char *kwlist[] = {"number", "ndigits", 0};
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002159
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002160 if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|i:round",
2161 kwlist, &number, &ndigits))
2162 return NULL;
2163 f = 1.0;
2164 i = abs(ndigits);
2165 while (--i >= 0)
2166 f = f*10.0;
2167 if (ndigits < 0)
2168 number /= f;
2169 else
2170 number *= f;
Mark Dickinsonf2637242009-11-09 17:45:40 +00002171
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002172 /* round `number` to nearest integer, rounding halves away from zero */
2173 abs_number = fabs(number);
2174 abs_result = floor(abs_number);
2175 if (abs_number - abs_result >= 0.5)
2176 abs_result += 1.0;
2177 number = copysign(abs_result, number);
Mark Dickinsonf2637242009-11-09 17:45:40 +00002178
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002179 if (ndigits < 0)
2180 number *= f;
2181 else
2182 number /= f;
2183 return PyFloat_FromDouble(number);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002184}
2185
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002186PyDoc_STRVAR(round_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002187"round(number[, ndigits]) -> floating point number\n\
2188\n\
2189Round a number to a given precision in decimal digits (default 0 digits).\n\
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +00002190This always returns a floating point number. Precision may be negative.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002191
Raymond Hettinger64958a12003-12-17 20:43:33 +00002192static PyObject *
2193builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2194{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002195 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
2196 PyObject *callable;
2197 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
2198 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002199
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002200 /* args 1-4 should match listsort in Objects/listobject.c */
2201 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
2202 kwlist, &seq, &compare, &keyfunc, &reverse))
2203 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002204
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002205 newlist = PySequence_List(seq);
2206 if (newlist == NULL)
2207 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002208
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002209 callable = PyObject_GetAttrString(newlist, "sort");
2210 if (callable == NULL) {
2211 Py_DECREF(newlist);
2212 return NULL;
2213 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002214
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002215 newargs = PyTuple_GetSlice(args, 1, 4);
2216 if (newargs == NULL) {
2217 Py_DECREF(newlist);
2218 Py_DECREF(callable);
2219 return NULL;
2220 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00002221
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002222 v = PyObject_Call(callable, newargs, kwds);
2223 Py_DECREF(newargs);
2224 Py_DECREF(callable);
2225 if (v == NULL) {
2226 Py_DECREF(newlist);
2227 return NULL;
2228 }
2229 Py_DECREF(v);
2230 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002231}
2232
2233PyDoc_STRVAR(sorted_doc,
2234"sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002235
Guido van Rossum79f25d91997-04-29 20:08:16 +00002236static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002237builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002238{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002239 PyObject *v = NULL;
2240 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002241
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002242 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2243 return NULL;
2244 if (v == NULL) {
2245 d = PyEval_GetLocals();
2246 if (d == NULL) {
2247 if (!PyErr_Occurred())
2248 PyErr_SetString(PyExc_SystemError,
2249 "vars(): no locals!?");
2250 }
2251 else
2252 Py_INCREF(d);
2253 }
2254 else {
2255 d = PyObject_GetAttrString(v, "__dict__");
2256 if (d == NULL) {
2257 PyErr_SetString(PyExc_TypeError,
2258 "vars() argument must have __dict__ attribute");
2259 return NULL;
2260 }
2261 }
2262 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002263}
2264
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002265PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002266"vars([object]) -> dictionary\n\
2267\n\
2268Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002269With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002270
Alex Martellia70b1912003-04-22 08:12:33 +00002271
2272static PyObject*
2273builtin_sum(PyObject *self, PyObject *args)
2274{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002275 PyObject *seq;
2276 PyObject *result = NULL;
2277 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002278
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002279 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
2280 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002281
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002282 iter = PyObject_GetIter(seq);
2283 if (iter == NULL)
2284 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002285
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002286 if (result == NULL) {
2287 result = PyInt_FromLong(0);
2288 if (result == NULL) {
2289 Py_DECREF(iter);
2290 return NULL;
2291 }
2292 } else {
2293 /* reject string values for 'start' parameter */
2294 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
2295 PyErr_SetString(PyExc_TypeError,
2296 "sum() can't sum strings [use ''.join(seq) instead]");
2297 Py_DECREF(iter);
2298 return NULL;
2299 }
2300 Py_INCREF(result);
2301 }
Alex Martellia70b1912003-04-22 08:12:33 +00002302
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002303#ifndef SLOW_SUM
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002304 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2305 Assumes all inputs are the same type. If the assumption fails, default
2306 to the more general routine.
2307 */
2308 if (PyInt_CheckExact(result)) {
2309 long i_result = PyInt_AS_LONG(result);
2310 Py_DECREF(result);
2311 result = NULL;
2312 while(result == NULL) {
2313 item = PyIter_Next(iter);
2314 if (item == NULL) {
2315 Py_DECREF(iter);
2316 if (PyErr_Occurred())
2317 return NULL;
2318 return PyInt_FromLong(i_result);
2319 }
2320 if (PyInt_CheckExact(item)) {
2321 long b = PyInt_AS_LONG(item);
2322 long x = i_result + b;
2323 if ((x^i_result) >= 0 || (x^b) >= 0) {
2324 i_result = x;
2325 Py_DECREF(item);
2326 continue;
2327 }
2328 }
2329 /* Either overflowed or is not an int. Restore real objects and process normally */
2330 result = PyInt_FromLong(i_result);
2331 temp = PyNumber_Add(result, item);
2332 Py_DECREF(result);
2333 Py_DECREF(item);
2334 result = temp;
2335 if (result == NULL) {
2336 Py_DECREF(iter);
2337 return NULL;
2338 }
2339 }
2340 }
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002341
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002342 if (PyFloat_CheckExact(result)) {
2343 double f_result = PyFloat_AS_DOUBLE(result);
2344 Py_DECREF(result);
2345 result = NULL;
2346 while(result == NULL) {
2347 item = PyIter_Next(iter);
2348 if (item == NULL) {
2349 Py_DECREF(iter);
2350 if (PyErr_Occurred())
2351 return NULL;
2352 return PyFloat_FromDouble(f_result);
2353 }
2354 if (PyFloat_CheckExact(item)) {
2355 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2356 f_result += PyFloat_AS_DOUBLE(item);
2357 PyFPE_END_PROTECT(f_result)
2358 Py_DECREF(item);
2359 continue;
2360 }
2361 if (PyInt_CheckExact(item)) {
2362 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2363 f_result += (double)PyInt_AS_LONG(item);
2364 PyFPE_END_PROTECT(f_result)
2365 Py_DECREF(item);
2366 continue;
2367 }
2368 result = PyFloat_FromDouble(f_result);
2369 temp = PyNumber_Add(result, item);
2370 Py_DECREF(result);
2371 Py_DECREF(item);
2372 result = temp;
2373 if (result == NULL) {
2374 Py_DECREF(iter);
2375 return NULL;
2376 }
2377 }
2378 }
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002379#endif
2380
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002381 for(;;) {
2382 item = PyIter_Next(iter);
2383 if (item == NULL) {
2384 /* error, or end-of-sequence */
2385 if (PyErr_Occurred()) {
2386 Py_DECREF(result);
2387 result = NULL;
2388 }
2389 break;
2390 }
2391 temp = PyNumber_Add(result, item);
2392 Py_DECREF(result);
2393 Py_DECREF(item);
2394 result = temp;
2395 if (result == NULL)
2396 break;
2397 }
2398 Py_DECREF(iter);
2399 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002400}
2401
2402PyDoc_STRVAR(sum_doc,
Georg Brandl8134d062006-10-12 12:33:07 +00002403"sum(sequence[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002404\n\
2405Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
Georg Brandl8134d062006-10-12 12:33:07 +00002406of parameter 'start' (which defaults to 0). When the sequence is\n\
2407empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002408
2409
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002410static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002411builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002412{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002413 PyObject *inst;
2414 PyObject *cls;
2415 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002416
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002417 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2418 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002419
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002420 retval = PyObject_IsInstance(inst, cls);
2421 if (retval < 0)
2422 return NULL;
2423 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002424}
2425
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002426PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002427"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002428\n\
2429Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002430With a type as second argument, return whether that is the object's type.\n\
2431The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002432isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002433
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002434
2435static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002436builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002437{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002438 PyObject *derived;
2439 PyObject *cls;
2440 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002441
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002442 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2443 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002444
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002445 retval = PyObject_IsSubclass(derived, cls);
2446 if (retval < 0)
2447 return NULL;
2448 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002449}
2450
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002451PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002452"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002453\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002454Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2455When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2456is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002457
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002458
Barry Warsawbd599b52000-08-03 15:45:29 +00002459static PyObject*
2460builtin_zip(PyObject *self, PyObject *args)
2461{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002462 PyObject *ret;
2463 const Py_ssize_t itemsize = PySequence_Length(args);
2464 Py_ssize_t i;
2465 PyObject *itlist; /* tuple of iterators */
2466 Py_ssize_t len; /* guess at result length */
Barry Warsawbd599b52000-08-03 15:45:29 +00002467
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002468 if (itemsize == 0)
2469 return PyList_New(0);
Raymond Hettingereaef6152003-08-02 07:42:57 +00002470
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002471 /* args must be a tuple */
2472 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002473
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002474 /* Guess at result length: the shortest of the input lengths.
2475 If some argument refuses to say, we refuse to guess too, lest
2476 an argument like xrange(sys.maxint) lead us astray.*/
2477 len = -1; /* unknown */
2478 for (i = 0; i < itemsize; ++i) {
2479 PyObject *item = PyTuple_GET_ITEM(args, i);
2480 Py_ssize_t thislen = _PyObject_LengthHint(item, -1);
2481 if (thislen < 0) {
2482 len = -1;
2483 break;
2484 }
2485 else if (len < 0 || thislen < len)
2486 len = thislen;
2487 }
Tim Peters67d687a2002-04-29 21:27:32 +00002488
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002489 /* allocate result list */
2490 if (len < 0)
2491 len = 10; /* arbitrary */
2492 if ((ret = PyList_New(len)) == NULL)
2493 return NULL;
Barry Warsawbd599b52000-08-03 15:45:29 +00002494
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002495 /* obtain iterators */
2496 itlist = PyTuple_New(itemsize);
2497 if (itlist == NULL)
2498 goto Fail_ret;
2499 for (i = 0; i < itemsize; ++i) {
2500 PyObject *item = PyTuple_GET_ITEM(args, i);
2501 PyObject *it = PyObject_GetIter(item);
2502 if (it == NULL) {
2503 if (PyErr_ExceptionMatches(PyExc_TypeError))
2504 PyErr_Format(PyExc_TypeError,
2505 "zip argument #%zd must support iteration",
2506 i+1);
2507 goto Fail_ret_itlist;
2508 }
2509 PyTuple_SET_ITEM(itlist, i, it);
2510 }
Barry Warsawbd599b52000-08-03 15:45:29 +00002511
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002512 /* build result into ret list */
2513 for (i = 0; ; ++i) {
2514 int j;
2515 PyObject *next = PyTuple_New(itemsize);
2516 if (!next)
2517 goto Fail_ret_itlist;
Tim Peters8572b4f2001-05-06 01:05:02 +00002518
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002519 for (j = 0; j < itemsize; j++) {
2520 PyObject *it = PyTuple_GET_ITEM(itlist, j);
2521 PyObject *item = PyIter_Next(it);
2522 if (!item) {
2523 if (PyErr_Occurred()) {
2524 Py_DECREF(ret);
2525 ret = NULL;
2526 }
2527 Py_DECREF(next);
2528 Py_DECREF(itlist);
2529 goto Done;
2530 }
2531 PyTuple_SET_ITEM(next, j, item);
2532 }
Tim Peters8572b4f2001-05-06 01:05:02 +00002533
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002534 if (i < len)
2535 PyList_SET_ITEM(ret, i, next);
2536 else {
2537 int status = PyList_Append(ret, next);
2538 Py_DECREF(next);
2539 ++len;
2540 if (status < 0)
2541 goto Fail_ret_itlist;
2542 }
2543 }
Tim Peters8572b4f2001-05-06 01:05:02 +00002544
Tim Peters67d687a2002-04-29 21:27:32 +00002545Done:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002546 if (ret != NULL && i < len) {
2547 /* The list is too big. */
2548 if (PyList_SetSlice(ret, i, len, NULL) < 0)
2549 return NULL;
2550 }
2551 return ret;
Tim Peters67d687a2002-04-29 21:27:32 +00002552
Tim Peters8572b4f2001-05-06 01:05:02 +00002553Fail_ret_itlist:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002554 Py_DECREF(itlist);
Tim Peters8572b4f2001-05-06 01:05:02 +00002555Fail_ret:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002556 Py_DECREF(ret);
2557 return NULL;
Barry Warsawbd599b52000-08-03 15:45:29 +00002558}
2559
2560
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002561PyDoc_STRVAR(zip_doc,
Barry Warsawbd599b52000-08-03 15:45:29 +00002562"zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2563\n\
2564Return a list of tuples, where each tuple contains the i-th element\n\
2565from each of the argument sequences. The returned list is truncated\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002566in length to the length of the shortest argument sequence.");
Barry Warsawbd599b52000-08-03 15:45:29 +00002567
2568
Guido van Rossum79f25d91997-04-29 20:08:16 +00002569static PyMethodDef builtin_methods[] = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002570 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2571 {"abs", builtin_abs, METH_O, abs_doc},
2572 {"all", builtin_all, METH_O, all_doc},
2573 {"any", builtin_any, METH_O, any_doc},
2574 {"apply", builtin_apply, METH_VARARGS, apply_doc},
2575 {"bin", builtin_bin, METH_O, bin_doc},
2576 {"callable", builtin_callable, METH_O, callable_doc},
2577 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2578 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
2579 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
2580 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2581 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2582 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2583 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2584 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2585 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
2586 {"filter", builtin_filter, METH_VARARGS, filter_doc},
2587 {"format", builtin_format, METH_VARARGS, format_doc},
2588 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2589 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2590 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2591 {"hash", builtin_hash, METH_O, hash_doc},
2592 {"hex", builtin_hex, METH_O, hex_doc},
2593 {"id", builtin_id, METH_O, id_doc},
2594 {"input", builtin_input, METH_VARARGS, input_doc},
2595 {"intern", builtin_intern, METH_VARARGS, intern_doc},
2596 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2597 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2598 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2599 {"len", builtin_len, METH_O, len_doc},
2600 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2601 {"map", builtin_map, METH_VARARGS, map_doc},
2602 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2603 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2604 {"next", builtin_next, METH_VARARGS, next_doc},
2605 {"oct", builtin_oct, METH_O, oct_doc},
2606 {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
2607 {"ord", builtin_ord, METH_O, ord_doc},
2608 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2609 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2610 {"range", builtin_range, METH_VARARGS, range_doc},
2611 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
2612 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
2613 {"reload", builtin_reload, METH_O, reload_doc},
2614 {"repr", builtin_repr, METH_O, repr_doc},
2615 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2616 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2617 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2618 {"sum", builtin_sum, METH_VARARGS, sum_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002619#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002620 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002621#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002622 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2623 {"zip", builtin_zip, METH_VARARGS, zip_doc},
2624 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002625};
2626
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002627PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002628"Built-in functions, exceptions, and other objects.\n\
2629\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002630Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002631
Guido van Rossum25ce5661997-08-02 03:10:38 +00002632PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002633_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002634{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002635 PyObject *mod, *dict, *debug;
2636 mod = Py_InitModule4("__builtin__", builtin_methods,
2637 builtin_doc, (PyObject *)NULL,
2638 PYTHON_API_VERSION);
2639 if (mod == NULL)
2640 return NULL;
2641 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002642
Tim Peters7571a0f2003-03-23 17:52:28 +00002643#ifdef Py_TRACE_REFS
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002644 /* __builtin__ exposes a number of statically allocated objects
2645 * that, before this code was added in 2.3, never showed up in
2646 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2647 * result, programs leaking references to None and False (etc)
2648 * couldn't be diagnosed by examining sys.getobjects(0).
2649 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002650#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2651#else
2652#define ADD_TO_ALL(OBJECT) (void)0
2653#endif
2654
Tim Peters4b7625e2001-09-13 21:37:17 +00002655#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002656 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2657 return NULL; \
2658 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002659
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002660 SETBUILTIN("None", Py_None);
2661 SETBUILTIN("Ellipsis", Py_Ellipsis);
2662 SETBUILTIN("NotImplemented", Py_NotImplemented);
2663 SETBUILTIN("False", Py_False);
2664 SETBUILTIN("True", Py_True);
2665 SETBUILTIN("basestring", &PyBaseString_Type);
2666 SETBUILTIN("bool", &PyBool_Type);
2667 /* SETBUILTIN("memoryview", &PyMemoryView_Type); */
2668 SETBUILTIN("bytearray", &PyByteArray_Type);
2669 SETBUILTIN("bytes", &PyString_Type);
2670 SETBUILTIN("buffer", &PyBuffer_Type);
2671 SETBUILTIN("classmethod", &PyClassMethod_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002672#ifndef WITHOUT_COMPLEX
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002673 SETBUILTIN("complex", &PyComplex_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002674#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002675 SETBUILTIN("dict", &PyDict_Type);
2676 SETBUILTIN("enumerate", &PyEnum_Type);
2677 SETBUILTIN("file", &PyFile_Type);
2678 SETBUILTIN("float", &PyFloat_Type);
2679 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2680 SETBUILTIN("property", &PyProperty_Type);
2681 SETBUILTIN("int", &PyInt_Type);
2682 SETBUILTIN("list", &PyList_Type);
2683 SETBUILTIN("long", &PyLong_Type);
2684 SETBUILTIN("object", &PyBaseObject_Type);
2685 SETBUILTIN("reversed", &PyReversed_Type);
2686 SETBUILTIN("set", &PySet_Type);
2687 SETBUILTIN("slice", &PySlice_Type);
2688 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2689 SETBUILTIN("str", &PyString_Type);
2690 SETBUILTIN("super", &PySuper_Type);
2691 SETBUILTIN("tuple", &PyTuple_Type);
2692 SETBUILTIN("type", &PyType_Type);
2693 SETBUILTIN("xrange", &PyRange_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002694#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002695 SETBUILTIN("unicode", &PyUnicode_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002696#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002697 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2698 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2699 Py_XDECREF(debug);
2700 return NULL;
2701 }
2702 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002703
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002704 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002705#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002706#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002707}
2708
Guido van Rossume77a7571993-11-03 15:01:26 +00002709/* Helper for filter(): filter a tuple through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002710
Guido van Rossum79f25d91997-04-29 20:08:16 +00002711static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002712filtertuple(PyObject *func, PyObject *tuple)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002713{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002714 PyObject *result;
2715 Py_ssize_t i, j;
2716 Py_ssize_t len = PyTuple_Size(tuple);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002717
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002718 if (len == 0) {
2719 if (PyTuple_CheckExact(tuple))
2720 Py_INCREF(tuple);
2721 else
2722 tuple = PyTuple_New(0);
2723 return tuple;
2724 }
Guido van Rossumb7b45621995-08-04 04:07:45 +00002725
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002726 if ((result = PyTuple_New(len)) == NULL)
2727 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002728
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002729 for (i = j = 0; i < len; ++i) {
2730 PyObject *item, *good;
2731 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002732
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002733 if (tuple->ob_type->tp_as_sequence &&
2734 tuple->ob_type->tp_as_sequence->sq_item) {
2735 item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
2736 if (item == NULL)
2737 goto Fail_1;
2738 } else {
2739 PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
2740 goto Fail_1;
2741 }
2742 if (func == Py_None) {
2743 Py_INCREF(item);
2744 good = item;
2745 }
2746 else {
2747 PyObject *arg = PyTuple_Pack(1, item);
2748 if (arg == NULL) {
2749 Py_DECREF(item);
2750 goto Fail_1;
2751 }
2752 good = PyEval_CallObject(func, arg);
2753 Py_DECREF(arg);
2754 if (good == NULL) {
2755 Py_DECREF(item);
2756 goto Fail_1;
2757 }
2758 }
2759 ok = PyObject_IsTrue(good);
2760 Py_DECREF(good);
2761 if (ok) {
2762 if (PyTuple_SetItem(result, j++, item) < 0)
2763 goto Fail_1;
2764 }
2765 else
2766 Py_DECREF(item);
2767 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002768
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002769 if (_PyTuple_Resize(&result, j) < 0)
2770 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002771
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002772 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002773
Guido van Rossum12d12c51993-10-26 17:58:25 +00002774Fail_1:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002775 Py_DECREF(result);
2776 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002777}
2778
2779
Guido van Rossume77a7571993-11-03 15:01:26 +00002780/* Helper for filter(): filter a string through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002781
Guido van Rossum79f25d91997-04-29 20:08:16 +00002782static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002783filterstring(PyObject *func, PyObject *strobj)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002784{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002785 PyObject *result;
2786 Py_ssize_t i, j;
2787 Py_ssize_t len = PyString_Size(strobj);
2788 Py_ssize_t outlen = len;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002789
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002790 if (func == Py_None) {
2791 /* If it's a real string we can return the original,
2792 * as no character is ever false and __getitem__
2793 * does return this character. If it's a subclass
2794 * we must go through the __getitem__ loop */
2795 if (PyString_CheckExact(strobj)) {
2796 Py_INCREF(strobj);
2797 return strobj;
2798 }
2799 }
2800 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2801 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002802
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002803 for (i = j = 0; i < len; ++i) {
2804 PyObject *item;
2805 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002806
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002807 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2808 if (item == NULL)
2809 goto Fail_1;
2810 if (func==Py_None) {
2811 ok = 1;
2812 } else {
2813 PyObject *arg, *good;
2814 arg = PyTuple_Pack(1, item);
2815 if (arg == NULL) {
2816 Py_DECREF(item);
2817 goto Fail_1;
2818 }
2819 good = PyEval_CallObject(func, arg);
2820 Py_DECREF(arg);
2821 if (good == NULL) {
2822 Py_DECREF(item);
2823 goto Fail_1;
2824 }
2825 ok = PyObject_IsTrue(good);
2826 Py_DECREF(good);
2827 }
2828 if (ok) {
2829 Py_ssize_t reslen;
2830 if (!PyString_Check(item)) {
2831 PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
2832 " __getitem__ returned different type");
2833 Py_DECREF(item);
2834 goto Fail_1;
2835 }
2836 reslen = PyString_GET_SIZE(item);
2837 if (reslen == 1) {
2838 PyString_AS_STRING(result)[j++] =
2839 PyString_AS_STRING(item)[0];
2840 } else {
2841 /* do we need more space? */
2842 Py_ssize_t need = j;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002843
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002844 /* calculate space requirements while checking for overflow */
2845 if (need > PY_SSIZE_T_MAX - reslen) {
2846 Py_DECREF(item);
2847 goto Fail_1;
2848 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002849
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002850 need += reslen;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002851
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002852 if (need > PY_SSIZE_T_MAX - len) {
2853 Py_DECREF(item);
2854 goto Fail_1;
2855 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002856
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002857 need += len;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002858
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002859 if (need <= i) {
2860 Py_DECREF(item);
2861 goto Fail_1;
2862 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002863
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002864 need = need - i - 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002865
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002866 assert(need >= 0);
2867 assert(outlen >= 0);
Gregory P. Smith9d534572008-06-11 07:41:16 +00002868
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002869 if (need > outlen) {
2870 /* overallocate, to avoid reallocations */
2871 if (outlen > PY_SSIZE_T_MAX / 2) {
2872 Py_DECREF(item);
2873 return NULL;
2874 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002875
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002876 if (need<2*outlen) {
2877 need = 2*outlen;
2878 }
2879 if (_PyString_Resize(&result, need)) {
2880 Py_DECREF(item);
2881 return NULL;
2882 }
2883 outlen = need;
2884 }
2885 memcpy(
2886 PyString_AS_STRING(result) + j,
2887 PyString_AS_STRING(item),
2888 reslen
2889 );
2890 j += reslen;
2891 }
2892 }
2893 Py_DECREF(item);
2894 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002895
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002896 if (j < outlen)
2897 _PyString_Resize(&result, j);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002898
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002899 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002900
Guido van Rossum12d12c51993-10-26 17:58:25 +00002901Fail_1:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002902 Py_DECREF(result);
2903 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002904}
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002905
2906#ifdef Py_USING_UNICODE
2907/* Helper for filter(): filter a Unicode object through a function */
2908
2909static PyObject *
2910filterunicode(PyObject *func, PyObject *strobj)
2911{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002912 PyObject *result;
2913 register Py_ssize_t i, j;
2914 Py_ssize_t len = PyUnicode_GetSize(strobj);
2915 Py_ssize_t outlen = len;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002916
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002917 if (func == Py_None) {
2918 /* If it's a real string we can return the original,
2919 * as no character is ever false and __getitem__
2920 * does return this character. If it's a subclass
2921 * we must go through the __getitem__ loop */
2922 if (PyUnicode_CheckExact(strobj)) {
2923 Py_INCREF(strobj);
2924 return strobj;
2925 }
2926 }
2927 if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
2928 return NULL;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002929
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002930 for (i = j = 0; i < len; ++i) {
2931 PyObject *item, *arg, *good;
2932 int ok;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002933
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002934 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2935 if (item == NULL)
2936 goto Fail_1;
2937 if (func == Py_None) {
2938 ok = 1;
2939 } else {
2940 arg = PyTuple_Pack(1, item);
2941 if (arg == NULL) {
2942 Py_DECREF(item);
2943 goto Fail_1;
2944 }
2945 good = PyEval_CallObject(func, arg);
2946 Py_DECREF(arg);
2947 if (good == NULL) {
2948 Py_DECREF(item);
2949 goto Fail_1;
2950 }
2951 ok = PyObject_IsTrue(good);
2952 Py_DECREF(good);
2953 }
2954 if (ok) {
2955 Py_ssize_t reslen;
2956 if (!PyUnicode_Check(item)) {
2957 PyErr_SetString(PyExc_TypeError,
2958 "can't filter unicode to unicode:"
2959 " __getitem__ returned different type");
2960 Py_DECREF(item);
2961 goto Fail_1;
2962 }
2963 reslen = PyUnicode_GET_SIZE(item);
2964 if (reslen == 1)
2965 PyUnicode_AS_UNICODE(result)[j++] =
2966 PyUnicode_AS_UNICODE(item)[0];
2967 else {
2968 /* do we need more space? */
2969 Py_ssize_t need = j + reslen + len - i - 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002970
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002971 /* check that didnt overflow */
2972 if ((j > PY_SSIZE_T_MAX - reslen) ||
2973 ((j + reslen) > PY_SSIZE_T_MAX - len) ||
2974 ((j + reslen + len) < i) ||
2975 ((j + reslen + len - i) <= 0)) {
2976 Py_DECREF(item);
2977 return NULL;
2978 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002979
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002980 assert(need >= 0);
2981 assert(outlen >= 0);
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002982
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002983 if (need > outlen) {
2984 /* overallocate,
2985 to avoid reallocations */
2986 if (need < 2 * outlen) {
2987 if (outlen > PY_SSIZE_T_MAX / 2) {
2988 Py_DECREF(item);
2989 return NULL;
2990 } else {
2991 need = 2 * outlen;
2992 }
2993 }
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002994
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002995 if (PyUnicode_Resize(
2996 &result, need) < 0) {
2997 Py_DECREF(item);
2998 goto Fail_1;
2999 }
3000 outlen = need;
3001 }
3002 memcpy(PyUnicode_AS_UNICODE(result) + j,
3003 PyUnicode_AS_UNICODE(item),
3004 reslen*sizeof(Py_UNICODE));
3005 j += reslen;
3006 }
3007 }
3008 Py_DECREF(item);
3009 }
3010
3011 if (j < outlen)
3012 PyUnicode_Resize(&result, j);
3013
3014 return result;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003015
3016Fail_1:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003017 Py_DECREF(result);
3018 return NULL;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003019}
3020#endif