blob: a9a7ad1009985e4db1c2b78526a0fbebb9e0f870 [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>
Mark Dickinsonbd15a062009-11-18 19:33:35 +000011#include <float.h> /* for DBL_MANT_DIG and friends */
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012
Guido van Rossume2ae77b2001-10-24 20:42:55 +000013#ifdef RISCOS
14#include "unixstuff.h"
15#endif
16
Mark Hammond26cffde2001-05-14 12:17:34 +000017/* The default encoding used by the platform file system APIs
18 Can remain NULL for all platforms that don't have such a concept
19*/
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000020#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Mark Hammond26cffde2001-05-14 12:17:34 +000021const char *Py_FileSystemDefaultEncoding = "mbcs";
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000022#elif defined(__APPLE__)
23const char *Py_FileSystemDefaultEncoding = "utf-8";
Mark Hammond26cffde2001-05-14 12:17:34 +000024#else
25const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
26#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000027
Guido van Rossum12d12c51993-10-26 17:58:25 +000028/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000029static PyObject *filterstring(PyObject *, PyObject *);
Martin v. Löwis8afd7572003-01-25 22:46:11 +000030#ifdef Py_USING_UNICODE
31static PyObject *filterunicode(PyObject *, PyObject *);
32#endif
Tim Petersdbd9ba62000-07-09 03:09:57 +000033static PyObject *filtertuple (PyObject *, PyObject *);
Guido van Rossum12d12c51993-10-26 17:58:25 +000034
Guido van Rossum79f25d91997-04-29 20:08:16 +000035static PyObject *
Neal Norwitz92e212f2006-04-03 04:48:37 +000036builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +000037{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000038 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
39 "level", 0};
40 char *name;
41 PyObject *globals = NULL;
42 PyObject *locals = NULL;
43 PyObject *fromlist = NULL;
44 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +000045
Antoine Pitrouc83ea132010-05-09 14:46:46 +000046 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
47 kwlist, &name, &globals, &locals, &fromlist, &level))
48 return NULL;
49 return PyImport_ImportModuleLevel(name, globals, locals,
50 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +000051}
52
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000053PyDoc_STRVAR(import_doc,
Neal Norwitz92e212f2006-04-03 04:48:37 +000054"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000055\n\
56Import a module. The globals are only used to determine the context;\n\
57they are not modified. The locals are currently unused. The fromlist\n\
58should be a list of names to emulate ``from name import ...'', or an\n\
59empty list to emulate ``import name''.\n\
60When importing a module from a package, note that __import__('A.B', ...)\n\
61returns package A when fromlist is empty, but its submodule B when\n\
Neal Norwitz92e212f2006-04-03 04:48:37 +000062fromlist is not empty. Level is used to determine whether to perform \n\
63absolute or relative imports. -1 is the original strategy of attempting\n\
64both absolute and relative imports, 0 is absolute, a positive number\n\
65is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000066
Guido van Rossum1ae940a1995-01-02 19:04:15 +000067
Guido van Rossum79f25d91997-04-29 20:08:16 +000068static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000069builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +000070{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000071 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +000072}
73
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000074PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000075"abs(number) -> number\n\
76\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000077Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000078
Raymond Hettinger96229b12005-03-11 06:49:40 +000079static PyObject *
80builtin_all(PyObject *self, PyObject *v)
81{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000082 PyObject *it, *item;
83 PyObject *(*iternext)(PyObject *);
84 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +000085
Antoine Pitrouc83ea132010-05-09 14:46:46 +000086 it = PyObject_GetIter(v);
87 if (it == NULL)
88 return NULL;
89 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +000090
Antoine Pitrouc83ea132010-05-09 14:46:46 +000091 for (;;) {
92 item = iternext(it);
93 if (item == NULL)
94 break;
95 cmp = PyObject_IsTrue(item);
96 Py_DECREF(item);
97 if (cmp < 0) {
98 Py_DECREF(it);
99 return NULL;
100 }
101 if (cmp == 0) {
102 Py_DECREF(it);
103 Py_RETURN_FALSE;
104 }
105 }
106 Py_DECREF(it);
107 if (PyErr_Occurred()) {
108 if (PyErr_ExceptionMatches(PyExc_StopIteration))
109 PyErr_Clear();
110 else
111 return NULL;
112 }
113 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000114}
115
116PyDoc_STRVAR(all_doc,
117"all(iterable) -> bool\n\
118\n\
119Return True if bool(x) is True for all values x in the iterable.");
120
121static PyObject *
122builtin_any(PyObject *self, PyObject *v)
123{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000124 PyObject *it, *item;
125 PyObject *(*iternext)(PyObject *);
126 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000127
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000128 it = PyObject_GetIter(v);
129 if (it == NULL)
130 return NULL;
131 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000132
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000133 for (;;) {
134 item = iternext(it);
135 if (item == NULL)
136 break;
137 cmp = PyObject_IsTrue(item);
138 Py_DECREF(item);
139 if (cmp < 0) {
140 Py_DECREF(it);
141 return NULL;
142 }
143 if (cmp == 1) {
144 Py_DECREF(it);
145 Py_RETURN_TRUE;
146 }
147 }
148 Py_DECREF(it);
149 if (PyErr_Occurred()) {
150 if (PyErr_ExceptionMatches(PyExc_StopIteration))
151 PyErr_Clear();
152 else
153 return NULL;
154 }
155 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000156}
157
158PyDoc_STRVAR(any_doc,
159"any(iterable) -> bool\n\
160\n\
161Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000162
Guido van Rossum79f25d91997-04-29 20:08:16 +0000163static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000164builtin_apply(PyObject *self, PyObject *args)
Guido van Rossumc02e15c1991-12-16 13:03:00 +0000165{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000166 PyObject *func, *alist = NULL, *kwdict = NULL;
167 PyObject *t = NULL, *retval = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000168
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000169 if (PyErr_WarnPy3k("apply() not supported in 3.x; "
170 "use func(*args, **kwargs)", 1) < 0)
171 return NULL;
Neal Norwitz8b2bfbc2007-05-23 06:35:32 +0000172
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000173 if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))
174 return NULL;
175 if (alist != NULL) {
176 if (!PyTuple_Check(alist)) {
177 if (!PySequence_Check(alist)) {
178 PyErr_Format(PyExc_TypeError,
179 "apply() arg 2 expected sequence, found %s",
180 alist->ob_type->tp_name);
181 return NULL;
182 }
183 t = PySequence_Tuple(alist);
184 if (t == NULL)
185 return NULL;
186 alist = t;
187 }
188 }
189 if (kwdict != NULL && !PyDict_Check(kwdict)) {
190 PyErr_Format(PyExc_TypeError,
191 "apply() arg 3 expected dictionary, found %s",
192 kwdict->ob_type->tp_name);
193 goto finally;
194 }
195 retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
Barry Warsaw968f8cb1998-10-01 15:33:12 +0000196 finally:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000197 Py_XDECREF(t);
198 return retval;
Guido van Rossumc02e15c1991-12-16 13:03:00 +0000199}
200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000201PyDoc_STRVAR(apply_doc,
Fred Drakef1fbc622001-01-12 17:05:05 +0000202"apply(object[, args[, kwargs]]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000203\n\
Fred Drake7b912121999-12-23 14:16:55 +0000204Call a callable object with positional arguments taken from the tuple args,\n\
205and keyword arguments taken from the optional dictionary kwargs.\n\
Raymond Hettingerff41c482003-04-06 09:01:11 +0000206Note that classes are callable, as are instances with a __call__() method.\n\
207\n\
208Deprecated since release 2.3. Instead, use the extended call syntax:\n\
209 function(*args, **keywords).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000210
211
Guido van Rossum79f25d91997-04-29 20:08:16 +0000212static PyObject *
Eric Smith3cd81942008-02-22 16:30:22 +0000213builtin_bin(PyObject *self, PyObject *v)
214{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000215 return PyNumber_ToBase(v, 2);
Eric Smith3cd81942008-02-22 16:30:22 +0000216}
217
218PyDoc_STRVAR(bin_doc,
219"bin(number) -> string\n\
220\n\
221Return the binary representation of an integer or long integer.");
222
223
224static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000225builtin_callable(PyObject *self, PyObject *v)
Guido van Rossum2d951851994-08-29 12:52:16 +0000226{
Victor Stinnerba8b3a22011-07-08 02:07:45 +0200227 if (PyErr_WarnPy3k("callable() not supported in 3.1; "
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000228 "use isinstance(x, collections.Callable)", 1) < 0)
229 return NULL;
230 return PyBool_FromLong((long)PyCallable_Check(v));
Guido van Rossum2d951851994-08-29 12:52:16 +0000231}
232
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000233PyDoc_STRVAR(callable_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000234"callable(object) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000235\n\
236Return whether the object is callable (i.e., some kind of function).\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000237Note that classes are callable, as are instances with a __call__() method.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000238
239
Guido van Rossum79f25d91997-04-29 20:08:16 +0000240static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000241builtin_filter(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000242{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000243 PyObject *func, *seq, *result, *it, *arg;
244 Py_ssize_t len; /* guess for result list size */
245 register Py_ssize_t j;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000246
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000247 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
248 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000249
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000250 /* Strings and tuples return a result of the same type. */
251 if (PyString_Check(seq))
252 return filterstring(func, seq);
Martin v. Löwis8afd7572003-01-25 22:46:11 +0000253#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000254 if (PyUnicode_Check(seq))
255 return filterunicode(func, seq);
Martin v. Löwis8afd7572003-01-25 22:46:11 +0000256#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000257 if (PyTuple_Check(seq))
258 return filtertuple(func, seq);
Tim Peters0e57abf2001-05-02 07:39:38 +0000259
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000260 /* Pre-allocate argument list tuple. */
261 arg = PyTuple_New(1);
262 if (arg == NULL)
263 return NULL;
Georg Brandle35b6572005-07-19 22:20:20 +0000264
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000265 /* Get iterator. */
266 it = PyObject_GetIter(seq);
267 if (it == NULL)
268 goto Fail_arg;
Tim Peters0e57abf2001-05-02 07:39:38 +0000269
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000270 /* Guess a result list size. */
271 len = _PyObject_LengthHint(seq, 8);
272 if (len == -1)
273 goto Fail_it;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000274
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000275 /* Get a result list. */
276 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
277 /* Eww - can modify the list in-place. */
278 Py_INCREF(seq);
279 result = seq;
280 }
281 else {
282 result = PyList_New(len);
283 if (result == NULL)
284 goto Fail_it;
285 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000286
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000287 /* Build the result list. */
288 j = 0;
289 for (;;) {
290 PyObject *item;
291 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000292
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000293 item = PyIter_Next(it);
294 if (item == NULL) {
295 if (PyErr_Occurred())
296 goto Fail_result_it;
297 break;
298 }
Guido van Rossumdc4b93d1993-10-27 14:56:44 +0000299
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000300 if (func == (PyObject *)&PyBool_Type || func == Py_None) {
301 ok = PyObject_IsTrue(item);
302 }
303 else {
304 PyObject *good;
305 PyTuple_SET_ITEM(arg, 0, item);
306 good = PyObject_Call(func, arg, NULL);
307 PyTuple_SET_ITEM(arg, 0, NULL);
308 if (good == NULL) {
309 Py_DECREF(item);
310 goto Fail_result_it;
311 }
312 ok = PyObject_IsTrue(good);
313 Py_DECREF(good);
314 }
315 if (ok) {
316 if (j < len)
317 PyList_SET_ITEM(result, j, item);
318 else {
319 int status = PyList_Append(result, item);
320 Py_DECREF(item);
321 if (status < 0)
322 goto Fail_result_it;
323 }
324 ++j;
325 }
326 else
327 Py_DECREF(item);
328 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000329
Guido van Rossum12d12c51993-10-26 17:58:25 +0000330
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000331 /* Cut back result list if len is too big. */
332 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
333 goto Fail_result_it;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000334
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000335 Py_DECREF(it);
336 Py_DECREF(arg);
337 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000338
Tim Peters0e57abf2001-05-02 07:39:38 +0000339Fail_result_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000340 Py_DECREF(result);
Tim Peters0e57abf2001-05-02 07:39:38 +0000341Fail_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000342 Py_DECREF(it);
Guido van Rossumc7903a12002-08-16 07:04:56 +0000343Fail_arg:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000344 Py_DECREF(arg);
345 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000346}
347
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000348PyDoc_STRVAR(filter_doc,
Tim Petersd50e5442002-03-09 00:06:26 +0000349"filter(function or None, sequence) -> list, tuple, or string\n"
350"\n"
351"Return those items of sequence for which function(item) is true. If\n"
352"function is None, return the items that are true. If sequence is a tuple\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000353"or string, return the same type, else return a list.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000354
Guido van Rossum79f25d91997-04-29 20:08:16 +0000355static PyObject *
Eric Smitha9f7d622008-02-17 19:46:49 +0000356builtin_format(PyObject *self, PyObject *args)
357{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000358 PyObject *value;
359 PyObject *format_spec = NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +0000360
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000361 if (!PyArg_ParseTuple(args, "O|O:format", &value, &format_spec))
362 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +0000363
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000364 return PyObject_Format(value, format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +0000365}
366
367PyDoc_STRVAR(format_doc,
368"format(value[, format_spec]) -> string\n\
369\n\
370Returns value.__format__(format_spec)\n\
371format_spec defaults to \"\"");
372
373static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000374builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000375{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000376 long x;
377 char s[1];
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000378
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000379 if (!PyArg_ParseTuple(args, "l:chr", &x))
380 return NULL;
381 if (x < 0 || x >= 256) {
382 PyErr_SetString(PyExc_ValueError,
383 "chr() arg not in range(256)");
384 return NULL;
385 }
386 s[0] = (char)x;
387 return PyString_FromStringAndSize(s, 1);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000388}
389
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000390PyDoc_STRVAR(chr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000391"chr(i) -> character\n\
392\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000393Return a string of one character with ordinal i; 0 <= i < 256.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000394
395
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000396#ifdef Py_USING_UNICODE
Guido van Rossum79f25d91997-04-29 20:08:16 +0000397static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000398builtin_unichr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000399{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000400 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000401
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000402 if (!PyArg_ParseTuple(args, "i:unichr", &x))
403 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000404
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000405 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000406}
407
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000408PyDoc_STRVAR(unichr_doc,
Fred Drake078b24f2000-04-13 02:42:50 +0000409"unichr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000410\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000411Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000412#endif
Guido van Rossum09095f32000-03-10 23:00:52 +0000413
414
415static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000416builtin_cmp(PyObject *self, PyObject *args)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000417{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000418 PyObject *a, *b;
419 int c;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000420
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000421 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
422 return NULL;
423 if (PyObject_Cmp(a, b, &c) < 0)
424 return NULL;
425 return PyInt_FromLong((long)c);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000426}
427
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000428PyDoc_STRVAR(cmp_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000429"cmp(x, y) -> integer\n\
430\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000431Return negative if x<y, zero if x==y, positive if x>y.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000432
433
Guido van Rossum79f25d91997-04-29 20:08:16 +0000434static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000435builtin_coerce(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000436{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000437 PyObject *v, *w;
438 PyObject *res;
Guido van Rossum5524a591995-01-10 15:26:20 +0000439
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000440 if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
441 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +0000442
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000443 if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
444 return NULL;
445 if (PyNumber_Coerce(&v, &w) < 0)
446 return NULL;
447 res = PyTuple_Pack(2, v, w);
448 Py_DECREF(v);
449 Py_DECREF(w);
450 return res;
Guido van Rossum04691fc1992-08-12 15:35:34 +0000451}
452
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000453PyDoc_STRVAR(coerce_doc,
Martin v. Löwis8d494f32004-08-25 10:42:41 +0000454"coerce(x, y) -> (x1, y1)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000455\n\
Martin v. Löwis8d494f32004-08-25 10:42:41 +0000456Return a tuple consisting of the two numeric arguments converted to\n\
457a common type, using the same rules as used by arithmetic operations.\n\
458If coercion is not possible, raise TypeError.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000459
Guido van Rossum79f25d91997-04-29 20:08:16 +0000460static PyObject *
Georg Brandl5240d742007-03-13 20:46:32 +0000461builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000462{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000463 char *str;
464 char *filename;
465 char *startstr;
466 int mode = -1;
467 int dont_inherit = 0;
468 int supplied_flags = 0;
469 int is_ast;
470 PyCompilerFlags cf;
471 PyObject *result = NULL, *cmd, *tmp = NULL;
472 Py_ssize_t length;
473 static char *kwlist[] = {"source", "filename", "mode", "flags",
474 "dont_inherit", NULL};
475 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000476
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000477 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
478 kwlist, &cmd, &filename, &startstr,
479 &supplied_flags, &dont_inherit))
480 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000481
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000482 cf.cf_flags = supplied_flags;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000483
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000484 if (supplied_flags &
485 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
486 {
487 PyErr_SetString(PyExc_ValueError,
488 "compile(): unrecognised flags");
489 return NULL;
490 }
491 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Georg Brandlfc8eef32008-03-28 12:11:56 +0000492
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000493 if (!dont_inherit) {
494 PyEval_MergeCompilerFlags(&cf);
495 }
Georg Brandlfc8eef32008-03-28 12:11:56 +0000496
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000497 if (strcmp(startstr, "exec") == 0)
498 mode = 0;
499 else if (strcmp(startstr, "eval") == 0)
500 mode = 1;
501 else if (strcmp(startstr, "single") == 0)
502 mode = 2;
503 else {
504 PyErr_SetString(PyExc_ValueError,
505 "compile() arg 3 must be 'exec', 'eval' or 'single'");
506 return NULL;
507 }
Georg Brandlf2bfd542008-03-29 13:24:23 +0000508
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000509 is_ast = PyAST_Check(cmd);
510 if (is_ast == -1)
511 return NULL;
512 if (is_ast) {
513 if (supplied_flags & PyCF_ONLY_AST) {
514 Py_INCREF(cmd);
515 result = cmd;
516 }
517 else {
518 PyArena *arena;
519 mod_ty mod;
Georg Brandlfc8eef32008-03-28 12:11:56 +0000520
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000521 arena = PyArena_New();
522 mod = PyAST_obj2mod(cmd, arena, mode);
523 if (mod == NULL) {
524 PyArena_Free(arena);
525 return NULL;
526 }
527 result = (PyObject*)PyAST_Compile(mod, filename,
528 &cf, arena);
529 PyArena_Free(arena);
530 }
531 return result;
532 }
Georg Brandlfc8eef32008-03-28 12:11:56 +0000533
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000534#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000535 if (PyUnicode_Check(cmd)) {
536 tmp = PyUnicode_AsUTF8String(cmd);
537 if (tmp == NULL)
538 return NULL;
539 cmd = tmp;
540 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
541 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000542#endif
Tim Peters6cd6a822001-08-17 22:11:27 +0000543
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000544 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))
545 goto cleanup;
546 if ((size_t)length != strlen(str)) {
547 PyErr_SetString(PyExc_TypeError,
548 "compile() expected string without null bytes");
549 goto cleanup;
550 }
551 result = Py_CompileStringFlags(str, filename, start[mode], &cf);
Neal Norwitz3a9a3e72005-11-27 20:38:31 +0000552cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000553 Py_XDECREF(tmp);
554 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000555}
556
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000557PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000558"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000559\n\
560Compile the source string (a Python module, statement or expression)\n\
561into a code object that can be executed by the exec statement or eval().\n\
562The filename will be used for run-time error messages.\n\
563The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000564single (interactive) statement, or 'eval' to compile an expression.\n\
565The flags argument, if present, controls which future statements influence\n\
566the compilation of the code.\n\
567The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
568the effects of any future statements in effect in the code calling\n\
569compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000570in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000571
Guido van Rossum79f25d91997-04-29 20:08:16 +0000572static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000573builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000574{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000575 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000576
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000577 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
578 return NULL;
579 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000580}
581
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000582PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000583"dir([object]) -> list of strings\n"
584"\n"
Georg Brandl871f1bc2007-03-12 13:17:36 +0000585"If called without an argument, return the names in the current scope.\n"
586"Else, return an alphabetized list of names comprising (some of) the attributes\n"
587"of the given object, and of attributes reachable from it.\n"
588"If the object supplies a method named __dir__, it will be used; otherwise\n"
589"the default dir() logic is used and returns:\n"
590" for a module object: the module's attributes.\n"
591" for a class object: its attributes, and recursively the attributes\n"
592" of its bases.\n"
Georg Brandl3bb15672007-03-13 07:23:16 +0000593" for any other object: its attributes, its class's attributes, and\n"
Georg Brandl871f1bc2007-03-12 13:17:36 +0000594" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000595
Guido van Rossum79f25d91997-04-29 20:08:16 +0000596static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000597builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000598{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000599 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000600
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000601 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
602 return NULL;
603 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000604}
605
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000606PyDoc_STRVAR(divmod_doc,
Raymond Hettinger39540a02011-07-19 11:59:20 -0700607"divmod(x, y) -> (quotient, remainder)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000608\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000609Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000610
611
Guido van Rossum79f25d91997-04-29 20:08:16 +0000612static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000613builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000614{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000615 PyObject *cmd, *result, *tmp = NULL;
616 PyObject *globals = Py_None, *locals = Py_None;
617 char *str;
618 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000619
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000620 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
621 return NULL;
622 if (locals != Py_None && !PyMapping_Check(locals)) {
623 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
624 return NULL;
625 }
626 if (globals != Py_None && !PyDict_Check(globals)) {
627 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
628 "globals must be a real dict; try eval(expr, {}, mapping)"
629 : "globals must be a dict");
630 return NULL;
631 }
632 if (globals == Py_None) {
633 globals = PyEval_GetGlobals();
634 if (locals == Py_None)
635 locals = PyEval_GetLocals();
636 }
637 else if (locals == Py_None)
638 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000639
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000640 if (globals == NULL || locals == NULL) {
641 PyErr_SetString(PyExc_TypeError,
642 "eval must be given globals and locals "
643 "when called without a frame");
644 return NULL;
645 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000646
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000647 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
648 if (PyDict_SetItemString(globals, "__builtins__",
649 PyEval_GetBuiltins()) != 0)
650 return NULL;
651 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000652
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000653 if (PyCode_Check(cmd)) {
654 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
655 PyErr_SetString(PyExc_TypeError,
656 "code object passed to eval() may not contain free variables");
657 return NULL;
658 }
659 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
660 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000661
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000662 if (!PyString_Check(cmd) &&
663 !PyUnicode_Check(cmd)) {
664 PyErr_SetString(PyExc_TypeError,
665 "eval() arg 1 must be a string or code object");
666 return NULL;
667 }
668 cf.cf_flags = 0;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000669
670#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000671 if (PyUnicode_Check(cmd)) {
672 tmp = PyUnicode_AsUTF8String(cmd);
673 if (tmp == NULL)
674 return NULL;
675 cmd = tmp;
676 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
677 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000678#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000679 if (PyString_AsStringAndSize(cmd, &str, NULL)) {
680 Py_XDECREF(tmp);
681 return NULL;
682 }
683 while (*str == ' ' || *str == '\t')
684 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000685
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000686 (void)PyEval_MergeCompilerFlags(&cf);
687 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
688 Py_XDECREF(tmp);
689 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000690}
691
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000692PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000693"eval(source[, globals[, locals]]) -> value\n\
694\n\
695Evaluate the source in the context of globals and locals.\n\
696The source may be a string representing a Python expression\n\
697or a code object as returned by compile().\n\
Neal Norwitz477ca1c2006-09-05 02:25:41 +0000698The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000699defaulting to the current globals and locals.\n\
700If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000701
702
Guido van Rossum79f25d91997-04-29 20:08:16 +0000703static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000704builtin_execfile(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000705{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000706 char *filename;
707 PyObject *globals = Py_None, *locals = Py_None;
708 PyObject *res;
709 FILE* fp = NULL;
710 PyCompilerFlags cf;
711 int exists;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000712
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000713 if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
714 1) < 0)
715 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +0000716
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000717 if (!PyArg_ParseTuple(args, "s|O!O:execfile",
718 &filename,
719 &PyDict_Type, &globals,
720 &locals))
721 return NULL;
722 if (locals != Py_None && !PyMapping_Check(locals)) {
723 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
724 return NULL;
725 }
726 if (globals == Py_None) {
727 globals = PyEval_GetGlobals();
728 if (locals == Py_None)
729 locals = PyEval_GetLocals();
730 }
731 else if (locals == Py_None)
732 locals = globals;
733 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
734 if (PyDict_SetItemString(globals, "__builtins__",
735 PyEval_GetBuiltins()) != 0)
736 return NULL;
737 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000738
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000739 exists = 0;
740 /* Test for existence or directory. */
Martin v. Löwis3484a182002-03-09 12:07:51 +0000741#if defined(PLAN9)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000742 {
743 Dir *d;
Martin v. Löwis3484a182002-03-09 12:07:51 +0000744
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000745 if ((d = dirstat(filename))!=nil) {
746 if(d->mode & DMDIR)
747 werrstr("is a directory");
748 else
749 exists = 1;
750 free(d);
751 }
752 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000753#elif defined(RISCOS)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000754 if (object_exists(filename)) {
755 if (isdir(filename))
756 errno = EISDIR;
757 else
758 exists = 1;
759 }
760#else /* standard Posix */
761 {
762 struct stat s;
763 if (stat(filename, &s) == 0) {
764 if (S_ISDIR(s.st_mode))
765# if defined(PYOS_OS2) && defined(PYCC_VACPP)
766 errno = EOS2ERR;
767# else
768 errno = EISDIR;
769# endif
770 else
771 exists = 1;
772 }
773 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000774#endif
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000775
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000776 if (exists) {
777 Py_BEGIN_ALLOW_THREADS
778 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
779 Py_END_ALLOW_THREADS
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000780
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000781 if (fp == NULL) {
782 exists = 0;
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000783 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000784 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000785
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000786 if (!exists) {
787 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
788 return NULL;
789 }
790 cf.cf_flags = 0;
791 if (PyEval_MergeCompilerFlags(&cf))
792 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
793 locals, 1, &cf);
794 else
795 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
796 locals, 1);
797 return res;
Guido van Rossum0f61f8a1992-02-25 18:55:05 +0000798}
799
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000800PyDoc_STRVAR(execfile_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000801"execfile(filename[, globals[, locals]])\n\
802\n\
803Read and execute a Python script from a file.\n\
804The globals and locals are dictionaries, defaulting to the current\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000805globals and locals. If only globals is given, locals defaults to it.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000806
807
Guido van Rossum79f25d91997-04-29 20:08:16 +0000808static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000809builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000810{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000811 PyObject *v, *result, *dflt = NULL;
812 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000813
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000814 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
815 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000816#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000817 if (PyUnicode_Check(name)) {
818 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
819 if (name == NULL)
820 return NULL;
821 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000822#endif
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000823
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000824 if (!PyString_Check(name)) {
825 PyErr_SetString(PyExc_TypeError,
826 "getattr(): attribute name must be string");
827 return NULL;
828 }
829 result = PyObject_GetAttr(v, name);
830 if (result == NULL && dflt != NULL &&
831 PyErr_ExceptionMatches(PyExc_AttributeError))
832 {
833 PyErr_Clear();
834 Py_INCREF(dflt);
835 result = dflt;
836 }
837 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000838}
839
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000840PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000841"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000842\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000843Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
844When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000845exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000846
847
Guido van Rossum79f25d91997-04-29 20:08:16 +0000848static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000849builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000850{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000851 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000852
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000853 d = PyEval_GetGlobals();
854 Py_XINCREF(d);
855 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000856}
857
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000858PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000859"globals() -> dictionary\n\
860\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000861Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000862
863
Guido van Rossum79f25d91997-04-29 20:08:16 +0000864static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000865builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000866{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000867 PyObject *v;
868 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000869
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000870 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
871 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000872#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000873 if (PyUnicode_Check(name)) {
874 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
875 if (name == NULL)
876 return NULL;
877 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000878#endif
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000879
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000880 if (!PyString_Check(name)) {
881 PyErr_SetString(PyExc_TypeError,
882 "hasattr(): attribute name must be string");
883 return NULL;
884 }
885 v = PyObject_GetAttr(v, name);
886 if (v == NULL) {
887 if (!PyErr_ExceptionMatches(PyExc_Exception))
888 return NULL;
889 else {
890 PyErr_Clear();
891 Py_INCREF(Py_False);
892 return Py_False;
893 }
894 }
895 Py_DECREF(v);
896 Py_INCREF(Py_True);
897 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000898}
899
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000900PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000901"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000902\n\
903Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000904(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000905
906
Guido van Rossum79f25d91997-04-29 20:08:16 +0000907static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000908builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000909{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000910 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000911}
912
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000913PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000914"id(object) -> integer\n\
915\n\
916Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000917simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000918
919
Guido van Rossum79f25d91997-04-29 20:08:16 +0000920static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000921builtin_map(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000922{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000923 typedef struct {
924 PyObject *it; /* the iterator object */
925 int saw_StopIteration; /* bool: did the iterator end? */
926 } sequence;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000927
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000928 PyObject *func, *result;
929 sequence *seqs = NULL, *sqp;
930 Py_ssize_t n, len;
931 register int i, j;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000932
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000933 n = PyTuple_Size(args);
934 if (n < 2) {
935 PyErr_SetString(PyExc_TypeError,
936 "map() requires at least two args");
937 return NULL;
938 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000939
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000940 func = PyTuple_GetItem(args, 0);
941 n--;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000942
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000943 if (func == Py_None) {
944 if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
945 "use list(...)", 1) < 0)
946 return NULL;
947 if (n == 1) {
948 /* map(None, S) is the same as list(S). */
949 return PySequence_List(PyTuple_GetItem(args, 1));
950 }
951 }
Guido van Rossumfa4ac711998-07-10 17:37:30 +0000952
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000953 /* Get space for sequence descriptors. Must NULL out the iterator
954 * pointers so that jumping to Fail_2 later doesn't see trash.
955 */
956 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
957 PyErr_NoMemory();
958 return NULL;
959 }
960 for (i = 0; i < n; ++i) {
961 seqs[i].it = (PyObject*)NULL;
962 seqs[i].saw_StopIteration = 0;
963 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000964
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000965 /* Do a first pass to obtain iterators for the arguments, and set len
966 * to the largest of their lengths.
967 */
968 len = 0;
969 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
970 PyObject *curseq;
971 Py_ssize_t curlen;
Guido van Rossumad991772001-01-12 16:03:05 +0000972
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000973 /* Get iterator. */
974 curseq = PyTuple_GetItem(args, i+1);
975 sqp->it = PyObject_GetIter(curseq);
976 if (sqp->it == NULL) {
977 static char errmsg[] =
978 "argument %d to map() must support iteration";
979 char errbuf[sizeof(errmsg) + 25];
980 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
981 PyErr_SetString(PyExc_TypeError, errbuf);
982 goto Fail_2;
983 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000984
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000985 /* Update len. */
986 curlen = _PyObject_LengthHint(curseq, 8);
987 if (curlen > len)
988 len = curlen;
989 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000990
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000991 /* Get space for the result list. */
992 if ((result = (PyObject *) PyList_New(len)) == NULL)
993 goto Fail_2;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000994
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000995 /* Iterate over the sequences until all have stopped. */
996 for (i = 0; ; ++i) {
997 PyObject *alist, *item=NULL, *value;
998 int numactive = 0;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000999
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001000 if (func == Py_None && n == 1)
1001 alist = NULL;
1002 else if ((alist = PyTuple_New(n)) == NULL)
1003 goto Fail_1;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001004
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001005 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
1006 if (sqp->saw_StopIteration) {
1007 Py_INCREF(Py_None);
1008 item = Py_None;
1009 }
1010 else {
1011 item = PyIter_Next(sqp->it);
1012 if (item)
1013 ++numactive;
1014 else {
1015 if (PyErr_Occurred()) {
1016 Py_XDECREF(alist);
1017 goto Fail_1;
1018 }
1019 Py_INCREF(Py_None);
1020 item = Py_None;
1021 sqp->saw_StopIteration = 1;
1022 }
1023 }
1024 if (alist)
1025 PyTuple_SET_ITEM(alist, j, item);
1026 else
1027 break;
1028 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001029
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001030 if (!alist)
1031 alist = item;
Guido van Rossum2d951851994-08-29 12:52:16 +00001032
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001033 if (numactive == 0) {
1034 Py_DECREF(alist);
1035 break;
1036 }
Guido van Rossum2d951851994-08-29 12:52:16 +00001037
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001038 if (func == Py_None)
1039 value = alist;
1040 else {
1041 value = PyEval_CallObject(func, alist);
1042 Py_DECREF(alist);
1043 if (value == NULL)
1044 goto Fail_1;
1045 }
1046 if (i >= len) {
1047 int status = PyList_Append(result, value);
1048 Py_DECREF(value);
1049 if (status < 0)
1050 goto Fail_1;
1051 }
1052 else if (PyList_SetItem(result, i, value) < 0)
1053 goto Fail_1;
1054 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001055
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001056 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
1057 goto Fail_1;
Guido van Rossumfa4ac711998-07-10 17:37:30 +00001058
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001059 goto Succeed;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001060
Guido van Rossum12d12c51993-10-26 17:58:25 +00001061Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001062 Py_DECREF(result);
Guido van Rossum12d12c51993-10-26 17:58:25 +00001063Fail_2:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001064 result = NULL;
Tim Peters4e9afdc2001-05-03 23:54:49 +00001065Succeed:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001066 assert(seqs);
1067 for (i = 0; i < n; ++i)
1068 Py_XDECREF(seqs[i].it);
1069 PyMem_DEL(seqs);
1070 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001071}
1072
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001073PyDoc_STRVAR(map_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001074"map(function, sequence[, sequence, ...]) -> list\n\
1075\n\
1076Return a list of the results of applying the function to the items of\n\
1077the argument sequence(s). If more than one sequence is given, the\n\
1078function is called with an argument list consisting of the corresponding\n\
1079item of each sequence, substituting None for missing values when not all\n\
1080sequences have the same length. If the function is None, return a list of\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001081the items of the sequence (or a list of tuples if more than one sequence).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001082
1083
Guido van Rossum79f25d91997-04-29 20:08:16 +00001084static PyObject *
Georg Brandl28e08732008-04-30 19:47:09 +00001085builtin_next(PyObject *self, PyObject *args)
1086{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001087 PyObject *it, *res;
1088 PyObject *def = NULL;
Georg Brandl28e08732008-04-30 19:47:09 +00001089
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001090 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1091 return NULL;
1092 if (!PyIter_Check(it)) {
1093 PyErr_Format(PyExc_TypeError,
1094 "%.200s object is not an iterator",
1095 it->ob_type->tp_name);
1096 return NULL;
1097 }
1098
1099 res = (*it->ob_type->tp_iternext)(it);
1100 if (res != NULL) {
1101 return res;
1102 } else if (def != NULL) {
1103 if (PyErr_Occurred()) {
1104 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
1105 return NULL;
1106 PyErr_Clear();
1107 }
1108 Py_INCREF(def);
1109 return def;
1110 } else if (PyErr_Occurred()) {
1111 return NULL;
1112 } else {
1113 PyErr_SetNone(PyExc_StopIteration);
1114 return NULL;
1115 }
Georg Brandl28e08732008-04-30 19:47:09 +00001116}
1117
1118PyDoc_STRVAR(next_doc,
1119"next(iterator[, default])\n\
1120\n\
1121Return the next item from the iterator. If default is given and the iterator\n\
1122is exhausted, it is returned instead of raising StopIteration.");
1123
1124
1125static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001126builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001127{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001128 PyObject *v;
1129 PyObject *name;
1130 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001131
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001132 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1133 return NULL;
1134 if (PyObject_SetAttr(v, name, value) != 0)
1135 return NULL;
1136 Py_INCREF(Py_None);
1137 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001138}
1139
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001140PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001141"setattr(object, name, value)\n\
1142\n\
1143Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001144``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001145
1146
Guido van Rossum79f25d91997-04-29 20:08:16 +00001147static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001148builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001149{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001150 PyObject *v;
1151 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001152
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001153 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1154 return NULL;
1155 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1156 return NULL;
1157 Py_INCREF(Py_None);
1158 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001159}
1160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001161PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001162"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001163\n\
1164Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001165``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001166
1167
Guido van Rossum79f25d91997-04-29 20:08:16 +00001168static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001169builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001170{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001171 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001172
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001173 x = PyObject_Hash(v);
1174 if (x == -1)
1175 return NULL;
1176 return PyInt_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001177}
1178
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001179PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001180"hash(object) -> integer\n\
1181\n\
1182Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001183the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001184
1185
Guido van Rossum79f25d91997-04-29 20:08:16 +00001186static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001187builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001188{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001189 PyNumberMethods *nb;
1190 PyObject *res;
Benjamin Petersonc6d64ec2008-05-17 20:09:42 +00001191
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001192 if ((nb = v->ob_type->tp_as_number) == NULL ||
1193 nb->nb_hex == NULL) {
1194 PyErr_SetString(PyExc_TypeError,
1195 "hex() argument can't be converted to hex");
1196 return NULL;
1197 }
1198 res = (*nb->nb_hex)(v);
1199 if (res && !PyString_Check(res)) {
1200 PyErr_Format(PyExc_TypeError,
1201 "__hex__ returned non-string (type %.200s)",
1202 res->ob_type->tp_name);
1203 Py_DECREF(res);
1204 return NULL;
1205 }
1206 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001207}
1208
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001209PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001210"hex(number) -> string\n\
1211\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001212Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001213
1214
Tim Petersdbd9ba62000-07-09 03:09:57 +00001215static PyObject *builtin_raw_input(PyObject *, PyObject *);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001216
Guido van Rossum79f25d91997-04-29 20:08:16 +00001217static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001218builtin_input(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001219{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001220 PyObject *line;
1221 char *str;
1222 PyObject *res;
1223 PyObject *globals, *locals;
1224 PyCompilerFlags cf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001225
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001226 line = builtin_raw_input(self, args);
1227 if (line == NULL)
1228 return line;
1229 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1230 return NULL;
1231 while (*str == ' ' || *str == '\t')
1232 str++;
1233 globals = PyEval_GetGlobals();
1234 locals = PyEval_GetLocals();
1235 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1236 if (PyDict_SetItemString(globals, "__builtins__",
1237 PyEval_GetBuiltins()) != 0)
1238 return NULL;
1239 }
1240 cf.cf_flags = 0;
1241 PyEval_MergeCompilerFlags(&cf);
1242 res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1243 Py_DECREF(line);
1244 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001245}
1246
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001247PyDoc_STRVAR(input_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001248"input([prompt]) -> value\n\
1249\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001250Equivalent to eval(raw_input(prompt)).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001251
1252
Guido van Rossume8811f81997-02-14 15:48:05 +00001253static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001254builtin_intern(PyObject *self, PyObject *args)
Guido van Rossume8811f81997-02-14 15:48:05 +00001255{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001256 PyObject *s;
1257 if (!PyArg_ParseTuple(args, "S:intern", &s))
1258 return NULL;
1259 if (!PyString_CheckExact(s)) {
1260 PyErr_SetString(PyExc_TypeError,
1261 "can't intern subclass of string");
1262 return NULL;
1263 }
1264 Py_INCREF(s);
1265 PyString_InternInPlace(&s);
1266 return s;
Guido van Rossume8811f81997-02-14 15:48:05 +00001267}
1268
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001269PyDoc_STRVAR(intern_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001270"intern(string) -> string\n\
1271\n\
1272``Intern'' the given string. This enters the string in the (global)\n\
1273table of interned strings whose purpose is to speed up dictionary lookups.\n\
1274Return the string itself or the previously interned string object with the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001275same value.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001276
1277
Guido van Rossum79f25d91997-04-29 20:08:16 +00001278static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001279builtin_iter(PyObject *self, PyObject *args)
1280{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001281 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001282
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001283 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1284 return NULL;
1285 if (w == NULL)
1286 return PyObject_GetIter(v);
1287 if (!PyCallable_Check(v)) {
1288 PyErr_SetString(PyExc_TypeError,
1289 "iter(v, w): v must be callable");
1290 return NULL;
1291 }
1292 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001293}
1294
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001295PyDoc_STRVAR(iter_doc,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001296"iter(collection) -> iterator\n\
1297iter(callable, sentinel) -> iterator\n\
1298\n\
1299Get an iterator from an object. In the first form, the argument must\n\
1300supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001301In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001302
1303
1304static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001305builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001306{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001307 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001308
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001309 res = PyObject_Size(v);
1310 if (res < 0 && PyErr_Occurred())
1311 return NULL;
1312 return PyInt_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001313}
1314
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001315PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001316"len(object) -> integer\n\
1317\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001318Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001319
1320
Guido van Rossum79f25d91997-04-29 20:08:16 +00001321static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001322builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001323{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001324 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001325
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001326 d = PyEval_GetLocals();
1327 Py_XINCREF(d);
1328 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001329}
1330
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001331PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001332"locals() -> dictionary\n\
1333\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001334Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001335
1336
Guido van Rossum79f25d91997-04-29 20:08:16 +00001337static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001338min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001339{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001340 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1341 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001342
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001343 if (PyTuple_Size(args) > 1)
1344 v = args;
1345 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1346 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001347
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001348 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1349 keyfunc = PyDict_GetItemString(kwds, "key");
1350 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1351 PyErr_Format(PyExc_TypeError,
1352 "%s() got an unexpected keyword argument", name);
1353 return NULL;
1354 }
1355 Py_INCREF(keyfunc);
1356 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001357
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001358 it = PyObject_GetIter(v);
1359 if (it == NULL) {
1360 Py_XDECREF(keyfunc);
1361 return NULL;
1362 }
Tim Petersc3074532001-05-03 07:00:32 +00001363
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001364 maxitem = NULL; /* the result */
1365 maxval = NULL; /* the value associated with the result */
1366 while (( item = PyIter_Next(it) )) {
1367 /* get the value from the key function */
1368 if (keyfunc != NULL) {
1369 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1370 if (val == NULL)
1371 goto Fail_it_item;
1372 }
1373 /* no key function; the value is the item */
1374 else {
1375 val = item;
1376 Py_INCREF(val);
1377 }
Tim Petersc3074532001-05-03 07:00:32 +00001378
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001379 /* maximum value and item are unset; set them */
1380 if (maxval == NULL) {
1381 maxitem = item;
1382 maxval = val;
1383 }
1384 /* maximum value and item are set; update them as necessary */
1385 else {
1386 int cmp = PyObject_RichCompareBool(val, maxval, op);
1387 if (cmp < 0)
1388 goto Fail_it_item_and_val;
1389 else if (cmp > 0) {
1390 Py_DECREF(maxval);
1391 Py_DECREF(maxitem);
1392 maxval = val;
1393 maxitem = item;
1394 }
1395 else {
1396 Py_DECREF(item);
1397 Py_DECREF(val);
1398 }
1399 }
1400 }
1401 if (PyErr_Occurred())
1402 goto Fail_it;
1403 if (maxval == NULL) {
1404 PyErr_Format(PyExc_ValueError,
1405 "%s() arg is an empty sequence", name);
1406 assert(maxitem == NULL);
1407 }
1408 else
1409 Py_DECREF(maxval);
1410 Py_DECREF(it);
1411 Py_XDECREF(keyfunc);
1412 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001413
1414Fail_it_item_and_val:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001415 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001416Fail_it_item:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001417 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001418Fail_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001419 Py_XDECREF(maxval);
1420 Py_XDECREF(maxitem);
1421 Py_DECREF(it);
1422 Py_XDECREF(keyfunc);
1423 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001424}
1425
Guido van Rossum79f25d91997-04-29 20:08:16 +00001426static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001427builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001428{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001429 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001430}
1431
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001432PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001433"min(iterable[, key=func]) -> value\n\
1434min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001435\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001436With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001437With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001438
1439
Guido van Rossum79f25d91997-04-29 20:08:16 +00001440static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001441builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001442{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001443 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001444}
1445
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001446PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001447"max(iterable[, key=func]) -> value\n\
1448max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001449\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001450With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001451With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001452
1453
Guido van Rossum79f25d91997-04-29 20:08:16 +00001454static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001455builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001456{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001457 PyNumberMethods *nb;
1458 PyObject *res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001459
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001460 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1461 nb->nb_oct == NULL) {
1462 PyErr_SetString(PyExc_TypeError,
1463 "oct() argument can't be converted to oct");
1464 return NULL;
1465 }
1466 res = (*nb->nb_oct)(v);
1467 if (res && !PyString_Check(res)) {
1468 PyErr_Format(PyExc_TypeError,
1469 "__oct__ returned non-string (type %.200s)",
1470 res->ob_type->tp_name);
1471 Py_DECREF(res);
1472 return NULL;
1473 }
1474 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001475}
1476
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001477PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001478"oct(number) -> string\n\
1479\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001480Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001481
1482
Guido van Rossum79f25d91997-04-29 20:08:16 +00001483static PyObject *
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001484builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
1485{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001486 return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001487}
1488
1489PyDoc_STRVAR(open_doc,
1490"open(name[, mode[, buffering]]) -> file object\n\
1491\n\
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00001492Open a file using the file() type, returns a file object. This is the\n\
Philip Jenveydd0388a2009-05-28 03:12:16 +00001493preferred way to open a file. See file.__doc__ for further information.");
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001494
1495
1496static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001497builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001498{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001499 long ord;
1500 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001501
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001502 if (PyString_Check(obj)) {
1503 size = PyString_GET_SIZE(obj);
1504 if (size == 1) {
1505 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1506 return PyInt_FromLong(ord);
1507 }
1508 } else if (PyByteArray_Check(obj)) {
1509 size = PyByteArray_GET_SIZE(obj);
1510 if (size == 1) {
1511 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1512 return PyInt_FromLong(ord);
1513 }
Christian Heimes1a6387e2008-03-26 12:49:49 +00001514
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001515#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001516 } else if (PyUnicode_Check(obj)) {
1517 size = PyUnicode_GET_SIZE(obj);
1518 if (size == 1) {
1519 ord = (long)*PyUnicode_AS_UNICODE(obj);
1520 return PyInt_FromLong(ord);
1521 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001522#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001523 } else {
1524 PyErr_Format(PyExc_TypeError,
1525 "ord() expected string of length 1, but " \
1526 "%.200s found", obj->ob_type->tp_name);
1527 return NULL;
1528 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001529
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001530 PyErr_Format(PyExc_TypeError,
1531 "ord() expected a character, "
1532 "but string of length %zd found",
1533 size);
1534 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001535}
1536
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001537PyDoc_STRVAR(ord_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001538"ord(c) -> integer\n\
1539\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001540Return the integer ordinal of a one-character string.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001541
1542
Guido van Rossum79f25d91997-04-29 20:08:16 +00001543static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001544builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001545{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001546 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001547
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001548 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1549 return NULL;
1550 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001551}
1552
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001553PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001554"pow(x, y[, z]) -> number\n\
1555\n\
1556With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001557equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001558
1559
Eric Smith7c478942008-03-18 23:45:49 +00001560static PyObject *
1561builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1562{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001563 static char *kwlist[] = {"sep", "end", "file", 0};
1564 static PyObject *dummy_args = NULL;
1565 static PyObject *unicode_newline = NULL, *unicode_space = NULL;
1566 static PyObject *str_newline = NULL, *str_space = NULL;
1567 PyObject *newline, *space;
1568 PyObject *sep = NULL, *end = NULL, *file = NULL;
1569 int i, err, use_unicode = 0;
Eric Smith7c478942008-03-18 23:45:49 +00001570
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001571 if (dummy_args == NULL) {
1572 if (!(dummy_args = PyTuple_New(0)))
1573 return NULL;
1574 }
1575 if (str_newline == NULL) {
1576 str_newline = PyString_FromString("\n");
1577 if (str_newline == NULL)
1578 return NULL;
1579 str_space = PyString_FromString(" ");
1580 if (str_space == NULL) {
1581 Py_CLEAR(str_newline);
1582 return NULL;
1583 }
1584 unicode_newline = PyUnicode_FromString("\n");
1585 if (unicode_newline == NULL) {
1586 Py_CLEAR(str_newline);
1587 Py_CLEAR(str_space);
1588 return NULL;
1589 }
1590 unicode_space = PyUnicode_FromString(" ");
1591 if (unicode_space == NULL) {
1592 Py_CLEAR(str_newline);
1593 Py_CLEAR(str_space);
1594 Py_CLEAR(unicode_space);
1595 return NULL;
1596 }
1597 }
1598 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1599 kwlist, &sep, &end, &file))
1600 return NULL;
1601 if (file == NULL || file == Py_None) {
1602 file = PySys_GetObject("stdout");
1603 /* sys.stdout may be None when FILE* stdout isn't connected */
1604 if (file == Py_None)
1605 Py_RETURN_NONE;
1606 }
1607 if (sep == Py_None) {
1608 sep = NULL;
1609 }
1610 else if (sep) {
1611 if (PyUnicode_Check(sep)) {
1612 use_unicode = 1;
1613 }
1614 else if (!PyString_Check(sep)) {
1615 PyErr_Format(PyExc_TypeError,
1616 "sep must be None, str or unicode, not %.200s",
1617 sep->ob_type->tp_name);
1618 return NULL;
1619 }
1620 }
1621 if (end == Py_None)
1622 end = NULL;
1623 else if (end) {
1624 if (PyUnicode_Check(end)) {
1625 use_unicode = 1;
1626 }
1627 else if (!PyString_Check(end)) {
1628 PyErr_Format(PyExc_TypeError,
1629 "end must be None, str or unicode, not %.200s",
1630 end->ob_type->tp_name);
1631 return NULL;
1632 }
1633 }
Benjamin Peterson753d1622009-07-02 18:16:45 +00001634
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001635 if (!use_unicode) {
1636 for (i = 0; i < PyTuple_Size(args); i++) {
1637 if (PyUnicode_Check(PyTuple_GET_ITEM(args, i))) {
1638 use_unicode = 1;
1639 break;
1640 }
1641 }
1642 }
1643 if (use_unicode) {
1644 newline = unicode_newline;
1645 space = unicode_space;
1646 }
1647 else {
1648 newline = str_newline;
1649 space = str_space;
1650 }
Eric Smith7c478942008-03-18 23:45:49 +00001651
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001652 for (i = 0; i < PyTuple_Size(args); i++) {
1653 if (i > 0) {
1654 if (sep == NULL)
1655 err = PyFile_WriteObject(space, file,
1656 Py_PRINT_RAW);
1657 else
1658 err = PyFile_WriteObject(sep, file,
1659 Py_PRINT_RAW);
1660 if (err)
1661 return NULL;
1662 }
1663 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1664 Py_PRINT_RAW);
1665 if (err)
1666 return NULL;
1667 }
Eric Smith7c478942008-03-18 23:45:49 +00001668
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001669 if (end == NULL)
1670 err = PyFile_WriteObject(newline, file, Py_PRINT_RAW);
1671 else
1672 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1673 if (err)
1674 return NULL;
Eric Smith7c478942008-03-18 23:45:49 +00001675
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001676 Py_RETURN_NONE;
Eric Smith7c478942008-03-18 23:45:49 +00001677}
1678
1679PyDoc_STRVAR(print_doc,
1680"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
1681\n\
1682Prints the values to a stream, or to sys.stdout by default.\n\
1683Optional keyword arguments:\n\
1684file: a file-like object (stream); defaults to the current sys.stdout.\n\
1685sep: string inserted between values, default a space.\n\
1686end: string appended after the last value, default a newline.");
1687
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001688
1689/* Return number of items in range (lo, hi, step), when arguments are
1690 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1691 * & only if the true value is too large to fit in a signed long.
1692 * Arguments MUST return 1 with either PyInt_Check() or
1693 * PyLong_Check(). Return -1 when there is an error.
1694 */
1695static long
1696get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
1697{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001698 /* -------------------------------------------------------------
1699 Algorithm is equal to that of get_len_of_range(), but it operates
1700 on PyObjects (which are assumed to be PyLong or PyInt objects).
1701 ---------------------------------------------------------------*/
1702 long n;
1703 PyObject *diff = NULL;
1704 PyObject *one = NULL;
1705 PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
1706 /* holds sub-expression evaluations */
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001707
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001708 /* if (lo >= hi), return length of 0. */
1709 if (PyObject_Compare(lo, hi) >= 0)
1710 return 0;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001711
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001712 if ((one = PyLong_FromLong(1L)) == NULL)
1713 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001714
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001715 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
1716 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001717
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001718 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
1719 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001720
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001721 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
1722 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001723
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001724 if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
1725 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001726
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001727 n = PyLong_AsLong(tmp3);
1728 if (PyErr_Occurred()) { /* Check for Overflow */
1729 PyErr_Clear();
1730 goto Fail;
1731 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001732
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001733 Py_DECREF(tmp3);
1734 Py_DECREF(tmp2);
1735 Py_DECREF(diff);
1736 Py_DECREF(tmp1);
1737 Py_DECREF(one);
1738 return n;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001739
1740 Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001741 Py_XDECREF(tmp3);
1742 Py_XDECREF(tmp2);
1743 Py_XDECREF(diff);
1744 Py_XDECREF(tmp1);
1745 Py_XDECREF(one);
1746 return -1;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001747}
1748
Mark Dickinsona8d26682010-05-04 16:18:25 +00001749/* Helper function for handle_range_longs. If arg is int or long
1750 object, returns it with incremented reference count. If arg is
1751 float, raises type error. As a last resort, creates a new int by
1752 calling arg type's nb_int method if it is defined. Returns NULL
1753 and sets exception on error.
1754
1755 Returns a new reference to an int object. */
1756static PyObject *
1757get_range_long_argument(PyObject *arg, const char *name)
1758{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001759 PyObject *v;
1760 PyNumberMethods *nb;
1761 if (PyInt_Check(arg) || PyLong_Check(arg)) {
1762 Py_INCREF(arg);
1763 return arg;
1764 }
1765 if (PyFloat_Check(arg) ||
1766 (nb = Py_TYPE(arg)->tp_as_number) == NULL ||
1767 nb->nb_int == NULL) {
1768 PyErr_Format(PyExc_TypeError,
1769 "range() integer %s argument expected, got %s.",
1770 name, arg->ob_type->tp_name);
1771 return NULL;
1772 }
1773 v = nb->nb_int(arg);
1774 if (v == NULL)
1775 return NULL;
1776 if (PyInt_Check(v) || PyLong_Check(v))
1777 return v;
1778 Py_DECREF(v);
1779 PyErr_SetString(PyExc_TypeError,
1780 "__int__ should return int object");
1781 return NULL;
Mark Dickinsona8d26682010-05-04 16:18:25 +00001782}
1783
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001784/* An extension of builtin_range() that handles the case when PyLong
1785 * arguments are given. */
1786static PyObject *
Mark Dickinsonef9b4ab2010-05-04 16:19:06 +00001787handle_range_longs(PyObject *self, PyObject *args)
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001788{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001789 PyObject *ilow = NULL;
1790 PyObject *ihigh = NULL;
1791 PyObject *istep = NULL;
Tim Peters874e1f72003-04-13 22:13:08 +00001792
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001793 PyObject *low = NULL;
1794 PyObject *high = NULL;
1795 PyObject *step = NULL;
Mark Dickinsona8d26682010-05-04 16:18:25 +00001796
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001797 PyObject *curnum = NULL;
1798 PyObject *v = NULL;
1799 long bign;
1800 Py_ssize_t i, n;
1801 int cmp_result;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001802
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001803 PyObject *zero = PyLong_FromLong(0);
Tim Peters874e1f72003-04-13 22:13:08 +00001804
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001805 if (zero == NULL)
1806 return NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001807
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001808 if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
1809 Py_DECREF(zero);
1810 return NULL;
1811 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001812
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001813 /* Figure out which way we were called, supply defaults, and be
1814 * sure to incref everything so that the decrefs at the end
1815 * are correct. NB: ilow, ihigh and istep are borrowed references.
1816 */
1817 assert(ilow != NULL);
1818 if (ihigh == NULL) {
1819 /* only 1 arg -- it's the upper limit */
1820 ihigh = ilow;
1821 ilow = NULL;
1822 }
Mark Dickinsona8d26682010-05-04 16:18:25 +00001823
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001824 /* convert ihigh if necessary */
1825 assert(ihigh != NULL);
1826 high = get_range_long_argument(ihigh, "end");
1827 if (high == NULL)
1828 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001829
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001830 /* ihigh correct now; do ilow */
1831 if (ilow == NULL) {
1832 Py_INCREF(zero);
1833 low = zero;
1834 }
1835 else {
1836 low = get_range_long_argument(ilow, "start");
1837 if (low == NULL)
1838 goto Fail;
1839 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001840
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001841 /* ilow and ihigh correct now; do istep */
1842 if (istep == NULL)
1843 step = PyLong_FromLong(1);
1844 else
1845 step = get_range_long_argument(istep, "step");
1846 if (step == NULL)
1847 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001848
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001849 if (PyObject_Cmp(step, zero, &cmp_result) == -1)
1850 goto Fail;
Tim Peters874e1f72003-04-13 22:13:08 +00001851
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001852 if (cmp_result == 0) {
1853 PyErr_SetString(PyExc_ValueError,
1854 "range() step argument must not be zero");
1855 goto Fail;
1856 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001857
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001858 if (cmp_result > 0)
1859 bign = get_len_of_range_longs(low, high, step);
1860 else {
1861 PyObject *neg_step = PyNumber_Negative(step);
1862 if (neg_step == NULL)
1863 goto Fail;
1864 bign = get_len_of_range_longs(high, low, neg_step);
1865 Py_DECREF(neg_step);
1866 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001867
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001868 n = (Py_ssize_t)bign;
1869 if (bign < 0 || (long)n != bign) {
1870 PyErr_SetString(PyExc_OverflowError,
1871 "range() result has too many items");
1872 goto Fail;
1873 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001874
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001875 v = PyList_New(n);
1876 if (v == NULL)
1877 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001878
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001879 curnum = low;
1880 Py_INCREF(curnum);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001881
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001882 for (i = 0; i < n; i++) {
1883 PyObject *w = PyNumber_Long(curnum);
1884 PyObject *tmp_num;
1885 if (w == NULL)
1886 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001887
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001888 PyList_SET_ITEM(v, i, w);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001889
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001890 tmp_num = PyNumber_Add(curnum, step);
1891 if (tmp_num == NULL)
1892 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001893
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001894 Py_DECREF(curnum);
1895 curnum = tmp_num;
1896 }
1897 Py_DECREF(low);
1898 Py_DECREF(high);
1899 Py_DECREF(step);
1900 Py_DECREF(zero);
1901 Py_DECREF(curnum);
1902 return v;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001903
1904 Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001905 Py_XDECREF(low);
1906 Py_XDECREF(high);
1907 Py_XDECREF(step);
1908 Py_DECREF(zero);
1909 Py_XDECREF(curnum);
1910 Py_XDECREF(v);
1911 return NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001912}
1913
Guido van Rossum124eff01999-02-23 16:11:01 +00001914/* Return number of items in range/xrange (lo, hi, step). step > 0
1915 * required. Return a value < 0 if & only if the true value is too
1916 * large to fit in a signed long.
1917 */
1918static long
Thomas Wouterse28c2962000-07-23 22:21:32 +00001919get_len_of_range(long lo, long hi, long step)
Guido van Rossum124eff01999-02-23 16:11:01 +00001920{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001921 /* -------------------------------------------------------------
1922 If lo >= hi, the range is empty.
1923 Else if n values are in the range, the last one is
1924 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1925 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1926 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1927 the RHS is non-negative and so truncation is the same as the
1928 floor. Letting M be the largest positive long, the worst case
1929 for the RHS numerator is hi=M, lo=-M-1, and then
1930 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1931 precision to compute the RHS exactly.
1932 ---------------------------------------------------------------*/
1933 long n = 0;
1934 if (lo < hi) {
1935 unsigned long uhi = (unsigned long)hi;
1936 unsigned long ulo = (unsigned long)lo;
1937 unsigned long diff = uhi - ulo - 1;
1938 n = (long)(diff / (unsigned long)step + 1);
1939 }
1940 return n;
Guido van Rossum124eff01999-02-23 16:11:01 +00001941}
1942
Guido van Rossum79f25d91997-04-29 20:08:16 +00001943static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001944builtin_range(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001945{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001946 long ilow = 0, ihigh = 0, istep = 1;
1947 long bign;
1948 Py_ssize_t i, n;
Guido van Rossum124eff01999-02-23 16:11:01 +00001949
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001950 PyObject *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001951
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001952 if (PyTuple_Size(args) <= 1) {
1953 if (!PyArg_ParseTuple(args,
1954 "l;range() requires 1-3 int arguments",
1955 &ihigh)) {
1956 PyErr_Clear();
1957 return handle_range_longs(self, args);
1958 }
1959 }
1960 else {
1961 if (!PyArg_ParseTuple(args,
1962 "ll|l;range() requires 1-3 int arguments",
1963 &ilow, &ihigh, &istep)) {
1964 PyErr_Clear();
1965 return handle_range_longs(self, args);
1966 }
1967 }
1968 if (istep == 0) {
1969 PyErr_SetString(PyExc_ValueError,
1970 "range() step argument must not be zero");
1971 return NULL;
1972 }
1973 if (istep > 0)
1974 bign = get_len_of_range(ilow, ihigh, istep);
1975 else
1976 bign = get_len_of_range(ihigh, ilow, -istep);
1977 n = (Py_ssize_t)bign;
1978 if (bign < 0 || (long)n != bign) {
1979 PyErr_SetString(PyExc_OverflowError,
1980 "range() result has too many items");
1981 return NULL;
1982 }
1983 v = PyList_New(n);
1984 if (v == NULL)
1985 return NULL;
1986 for (i = 0; i < n; i++) {
1987 PyObject *w = PyInt_FromLong(ilow);
1988 if (w == NULL) {
1989 Py_DECREF(v);
1990 return NULL;
1991 }
1992 PyList_SET_ITEM(v, i, w);
1993 ilow += istep;
1994 }
1995 return v;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001996}
1997
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001998PyDoc_STRVAR(range_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001999"range([start,] stop[, step]) -> list of integers\n\
2000\n\
2001Return a list containing an arithmetic progression of integers.\n\
2002range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
2003When step is given, it specifies the increment (or decrement).\n\
2004For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002005These are exactly the valid indices for a list of 4 elements.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002006
2007
Guido van Rossum79f25d91997-04-29 20:08:16 +00002008static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002009builtin_raw_input(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002010{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002011 PyObject *v = NULL;
2012 PyObject *fin = PySys_GetObject("stdin");
2013 PyObject *fout = PySys_GetObject("stdout");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002014
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002015 if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
2016 return NULL;
Martin v. Löwis31d2df52002-08-14 15:46:02 +00002017
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002018 if (fin == NULL) {
2019 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
2020 return NULL;
2021 }
2022 if (fout == NULL) {
2023 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
2024 return NULL;
2025 }
2026 if (PyFile_SoftSpace(fout, 0)) {
2027 if (PyFile_WriteString(" ", fout) != 0)
2028 return NULL;
2029 }
2030 if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
2031 && isatty(fileno(PyFile_AsFile(fin)))
2032 && isatty(fileno(PyFile_AsFile(fout)))) {
2033 PyObject *po;
2034 char *prompt;
2035 char *s;
2036 PyObject *result;
2037 if (v != NULL) {
2038 po = PyObject_Str(v);
2039 if (po == NULL)
2040 return NULL;
2041 prompt = PyString_AsString(po);
2042 if (prompt == NULL)
2043 return NULL;
2044 }
2045 else {
2046 po = NULL;
2047 prompt = "";
2048 }
2049 s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
2050 prompt);
2051 Py_XDECREF(po);
2052 if (s == NULL) {
2053 if (!PyErr_Occurred())
2054 PyErr_SetNone(PyExc_KeyboardInterrupt);
2055 return NULL;
2056 }
2057 if (*s == '\0') {
2058 PyErr_SetNone(PyExc_EOFError);
2059 result = NULL;
2060 }
2061 else { /* strip trailing '\n' */
2062 size_t len = strlen(s);
2063 if (len > PY_SSIZE_T_MAX) {
2064 PyErr_SetString(PyExc_OverflowError,
2065 "[raw_]input: input too long");
2066 result = NULL;
2067 }
2068 else {
2069 result = PyString_FromStringAndSize(s, len-1);
2070 }
2071 }
2072 PyMem_FREE(s);
2073 return result;
2074 }
2075 if (v != NULL) {
2076 if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
2077 return NULL;
2078 }
2079 return PyFile_GetLine(fin, -1);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002080}
2081
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002082PyDoc_STRVAR(raw_input_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002083"raw_input([prompt]) -> string\n\
2084\n\
2085Read a string from standard input. The trailing newline is stripped.\n\
2086If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
2087On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002088is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002089
2090
Guido van Rossum79f25d91997-04-29 20:08:16 +00002091static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002092builtin_reduce(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002093{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002094 static PyObject *functools_reduce = NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002095
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002096 if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
2097 "use functools.reduce()", 1) < 0)
2098 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +00002099
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002100 if (functools_reduce == NULL) {
2101 PyObject *functools = PyImport_ImportModule("functools");
2102 if (functools == NULL)
2103 return NULL;
2104 functools_reduce = PyObject_GetAttrString(functools, "reduce");
2105 Py_DECREF(functools);
2106 if (functools_reduce == NULL)
2107 return NULL;
2108 }
2109 return PyObject_Call(functools_reduce, args, NULL);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002110}
2111
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002112PyDoc_STRVAR(reduce_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002113"reduce(function, sequence[, initial]) -> value\n\
2114\n\
2115Apply a function of two arguments cumulatively to the items of a sequence,\n\
2116from left to right, so as to reduce the sequence to a single value.\n\
2117For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
2118((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
2119of the sequence in the calculation, and serves as a default when the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002120sequence is empty.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002121
2122
Guido van Rossum79f25d91997-04-29 20:08:16 +00002123static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002124builtin_reload(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002125{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002126 if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
2127 1) < 0)
2128 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +00002129
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002130 return PyImport_ReloadModule(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002131}
2132
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002133PyDoc_STRVAR(reload_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002134"reload(module) -> module\n\
2135\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002136Reload the module. The module must have been successfully imported before.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002137
2138
Guido van Rossum79f25d91997-04-29 20:08:16 +00002139static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002140builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00002141{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002142 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002143}
2144
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002145PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002146"repr(object) -> string\n\
2147\n\
2148Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002149For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002150
2151
Guido van Rossum79f25d91997-04-29 20:08:16 +00002152static PyObject *
Georg Brandlccadf842006-03-31 18:54:53 +00002153builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002154{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002155 double x;
2156 PyObject *o_ndigits = NULL;
2157 Py_ssize_t ndigits;
2158 static char *kwlist[] = {"number", "ndigits", 0};
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002159
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002160 if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|O:round",
2161 kwlist, &x, &o_ndigits))
2162 return NULL;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002163
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002164 if (o_ndigits == NULL) {
2165 /* second argument defaults to 0 */
2166 ndigits = 0;
2167 }
2168 else {
2169 /* interpret 2nd argument as a Py_ssize_t; clip on overflow */
2170 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
2171 if (ndigits == -1 && PyErr_Occurred())
2172 return NULL;
2173 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002174
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002175 /* nans, infinities and zeros round to themselves */
2176 if (!Py_IS_FINITE(x) || x == 0.0)
2177 return PyFloat_FromDouble(x);
Mark Dickinsonbce78372009-11-24 10:54:58 +00002178
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002179 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
2180 always rounds to itself. For ndigits < NDIGITS_MIN, x always
2181 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002182#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
2183#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002184 if (ndigits > NDIGITS_MAX)
2185 /* return x */
2186 return PyFloat_FromDouble(x);
2187 else if (ndigits < NDIGITS_MIN)
2188 /* return 0.0, but with sign of x */
2189 return PyFloat_FromDouble(0.0*x);
2190 else
2191 /* finite x, and ndigits is not unreasonably large */
2192 /* _Py_double_round is defined in floatobject.c */
2193 return _Py_double_round(x, (int)ndigits);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002194#undef NDIGITS_MAX
2195#undef NDIGITS_MIN
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002196}
2197
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002198PyDoc_STRVAR(round_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002199"round(number[, ndigits]) -> floating point number\n\
2200\n\
2201Round a number to a given precision in decimal digits (default 0 digits).\n\
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +00002202This always returns a floating point number. Precision may be negative.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002203
Raymond Hettinger64958a12003-12-17 20:43:33 +00002204static PyObject *
2205builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2206{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002207 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
2208 PyObject *callable;
2209 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
2210 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002211
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002212 /* args 1-4 should match listsort in Objects/listobject.c */
2213 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
2214 kwlist, &seq, &compare, &keyfunc, &reverse))
2215 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002216
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002217 newlist = PySequence_List(seq);
2218 if (newlist == NULL)
2219 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002220
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002221 callable = PyObject_GetAttrString(newlist, "sort");
2222 if (callable == NULL) {
2223 Py_DECREF(newlist);
2224 return NULL;
2225 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002226
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002227 newargs = PyTuple_GetSlice(args, 1, 4);
2228 if (newargs == NULL) {
2229 Py_DECREF(newlist);
2230 Py_DECREF(callable);
2231 return NULL;
2232 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00002233
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002234 v = PyObject_Call(callable, newargs, kwds);
2235 Py_DECREF(newargs);
2236 Py_DECREF(callable);
2237 if (v == NULL) {
2238 Py_DECREF(newlist);
2239 return NULL;
2240 }
2241 Py_DECREF(v);
2242 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002243}
2244
2245PyDoc_STRVAR(sorted_doc,
2246"sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002247
Guido van Rossum79f25d91997-04-29 20:08:16 +00002248static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002249builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002250{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002251 PyObject *v = NULL;
2252 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002253
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002254 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2255 return NULL;
2256 if (v == NULL) {
2257 d = PyEval_GetLocals();
2258 if (d == NULL) {
2259 if (!PyErr_Occurred())
2260 PyErr_SetString(PyExc_SystemError,
2261 "vars(): no locals!?");
2262 }
2263 else
2264 Py_INCREF(d);
2265 }
2266 else {
2267 d = PyObject_GetAttrString(v, "__dict__");
2268 if (d == NULL) {
2269 PyErr_SetString(PyExc_TypeError,
2270 "vars() argument must have __dict__ attribute");
2271 return NULL;
2272 }
2273 }
2274 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002275}
2276
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002277PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002278"vars([object]) -> dictionary\n\
2279\n\
2280Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002281With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002282
Alex Martellia70b1912003-04-22 08:12:33 +00002283
2284static PyObject*
2285builtin_sum(PyObject *self, PyObject *args)
2286{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002287 PyObject *seq;
2288 PyObject *result = NULL;
2289 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002290
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002291 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
2292 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002293
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002294 iter = PyObject_GetIter(seq);
2295 if (iter == NULL)
2296 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002297
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002298 if (result == NULL) {
2299 result = PyInt_FromLong(0);
2300 if (result == NULL) {
2301 Py_DECREF(iter);
2302 return NULL;
2303 }
2304 } else {
2305 /* reject string values for 'start' parameter */
2306 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
2307 PyErr_SetString(PyExc_TypeError,
2308 "sum() can't sum strings [use ''.join(seq) instead]");
2309 Py_DECREF(iter);
2310 return NULL;
2311 }
2312 Py_INCREF(result);
2313 }
Alex Martellia70b1912003-04-22 08:12:33 +00002314
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002315#ifndef SLOW_SUM
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002316 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2317 Assumes all inputs are the same type. If the assumption fails, default
2318 to the more general routine.
2319 */
2320 if (PyInt_CheckExact(result)) {
2321 long i_result = PyInt_AS_LONG(result);
2322 Py_DECREF(result);
2323 result = NULL;
2324 while(result == NULL) {
2325 item = PyIter_Next(iter);
2326 if (item == NULL) {
2327 Py_DECREF(iter);
2328 if (PyErr_Occurred())
2329 return NULL;
2330 return PyInt_FromLong(i_result);
2331 }
2332 if (PyInt_CheckExact(item)) {
2333 long b = PyInt_AS_LONG(item);
2334 long x = i_result + b;
2335 if ((x^i_result) >= 0 || (x^b) >= 0) {
2336 i_result = x;
2337 Py_DECREF(item);
2338 continue;
2339 }
2340 }
2341 /* Either overflowed or is not an int. Restore real objects and process normally */
2342 result = PyInt_FromLong(i_result);
2343 temp = PyNumber_Add(result, item);
2344 Py_DECREF(result);
2345 Py_DECREF(item);
2346 result = temp;
2347 if (result == NULL) {
2348 Py_DECREF(iter);
2349 return NULL;
2350 }
2351 }
2352 }
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002353
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002354 if (PyFloat_CheckExact(result)) {
2355 double f_result = PyFloat_AS_DOUBLE(result);
2356 Py_DECREF(result);
2357 result = NULL;
2358 while(result == NULL) {
2359 item = PyIter_Next(iter);
2360 if (item == NULL) {
2361 Py_DECREF(iter);
2362 if (PyErr_Occurred())
2363 return NULL;
2364 return PyFloat_FromDouble(f_result);
2365 }
2366 if (PyFloat_CheckExact(item)) {
2367 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2368 f_result += PyFloat_AS_DOUBLE(item);
2369 PyFPE_END_PROTECT(f_result)
2370 Py_DECREF(item);
2371 continue;
2372 }
2373 if (PyInt_CheckExact(item)) {
2374 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2375 f_result += (double)PyInt_AS_LONG(item);
2376 PyFPE_END_PROTECT(f_result)
2377 Py_DECREF(item);
2378 continue;
2379 }
2380 result = PyFloat_FromDouble(f_result);
2381 temp = PyNumber_Add(result, item);
2382 Py_DECREF(result);
2383 Py_DECREF(item);
2384 result = temp;
2385 if (result == NULL) {
2386 Py_DECREF(iter);
2387 return NULL;
2388 }
2389 }
2390 }
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002391#endif
2392
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002393 for(;;) {
2394 item = PyIter_Next(iter);
2395 if (item == NULL) {
2396 /* error, or end-of-sequence */
2397 if (PyErr_Occurred()) {
2398 Py_DECREF(result);
2399 result = NULL;
2400 }
2401 break;
2402 }
2403 /* It's tempting to use PyNumber_InPlaceAdd instead of
2404 PyNumber_Add here, to avoid quadratic running time
2405 when doing 'sum(list_of_lists, [])'. However, this
2406 would produce a change in behaviour: a snippet like
Mark Dickinson0e0e2152009-10-26 14:18:44 +00002407
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002408 empty = []
2409 sum([[x] for x in range(10)], empty)
Mark Dickinson0e0e2152009-10-26 14:18:44 +00002410
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002411 would change the value of empty. */
2412 temp = PyNumber_Add(result, item);
2413 Py_DECREF(result);
2414 Py_DECREF(item);
2415 result = temp;
2416 if (result == NULL)
2417 break;
2418 }
2419 Py_DECREF(iter);
2420 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002421}
2422
2423PyDoc_STRVAR(sum_doc,
Georg Brandl8134d062006-10-12 12:33:07 +00002424"sum(sequence[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002425\n\
2426Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
Georg Brandl8134d062006-10-12 12:33:07 +00002427of parameter 'start' (which defaults to 0). When the sequence is\n\
2428empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002429
2430
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002431static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002432builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002433{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002434 PyObject *inst;
2435 PyObject *cls;
2436 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002437
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002438 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2439 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002440
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002441 retval = PyObject_IsInstance(inst, cls);
2442 if (retval < 0)
2443 return NULL;
2444 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002445}
2446
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002447PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002448"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002449\n\
2450Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002451With a type as second argument, return whether that is the object's type.\n\
2452The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002453isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002454
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002455
2456static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002457builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002458{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002459 PyObject *derived;
2460 PyObject *cls;
2461 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002462
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002463 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2464 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002465
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002466 retval = PyObject_IsSubclass(derived, cls);
2467 if (retval < 0)
2468 return NULL;
2469 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002470}
2471
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002472PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002473"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002474\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002475Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2476When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2477is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002478
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002479
Barry Warsawbd599b52000-08-03 15:45:29 +00002480static PyObject*
2481builtin_zip(PyObject *self, PyObject *args)
2482{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002483 PyObject *ret;
2484 const Py_ssize_t itemsize = PySequence_Length(args);
2485 Py_ssize_t i;
2486 PyObject *itlist; /* tuple of iterators */
2487 Py_ssize_t len; /* guess at result length */
Barry Warsawbd599b52000-08-03 15:45:29 +00002488
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002489 if (itemsize == 0)
2490 return PyList_New(0);
Raymond Hettingereaef6152003-08-02 07:42:57 +00002491
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002492 /* args must be a tuple */
2493 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002494
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002495 /* Guess at result length: the shortest of the input lengths.
2496 If some argument refuses to say, we refuse to guess too, lest
2497 an argument like xrange(sys.maxint) lead us astray.*/
2498 len = -1; /* unknown */
2499 for (i = 0; i < itemsize; ++i) {
2500 PyObject *item = PyTuple_GET_ITEM(args, i);
2501 Py_ssize_t thislen = _PyObject_LengthHint(item, -2);
2502 if (thislen < 0) {
2503 if (thislen == -1)
2504 return NULL;
2505 len = -1;
2506 break;
2507 }
2508 else if (len < 0 || thislen < len)
2509 len = thislen;
2510 }
Tim Peters67d687a2002-04-29 21:27:32 +00002511
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002512 /* allocate result list */
2513 if (len < 0)
2514 len = 10; /* arbitrary */
2515 if ((ret = PyList_New(len)) == NULL)
2516 return NULL;
Barry Warsawbd599b52000-08-03 15:45:29 +00002517
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002518 /* obtain iterators */
2519 itlist = PyTuple_New(itemsize);
2520 if (itlist == NULL)
2521 goto Fail_ret;
2522 for (i = 0; i < itemsize; ++i) {
2523 PyObject *item = PyTuple_GET_ITEM(args, i);
2524 PyObject *it = PyObject_GetIter(item);
2525 if (it == NULL) {
2526 if (PyErr_ExceptionMatches(PyExc_TypeError))
2527 PyErr_Format(PyExc_TypeError,
2528 "zip argument #%zd must support iteration",
2529 i+1);
2530 goto Fail_ret_itlist;
2531 }
2532 PyTuple_SET_ITEM(itlist, i, it);
2533 }
Barry Warsawbd599b52000-08-03 15:45:29 +00002534
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002535 /* build result into ret list */
2536 for (i = 0; ; ++i) {
2537 int j;
2538 PyObject *next = PyTuple_New(itemsize);
2539 if (!next)
2540 goto Fail_ret_itlist;
Tim Peters8572b4f2001-05-06 01:05:02 +00002541
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002542 for (j = 0; j < itemsize; j++) {
2543 PyObject *it = PyTuple_GET_ITEM(itlist, j);
2544 PyObject *item = PyIter_Next(it);
2545 if (!item) {
2546 if (PyErr_Occurred()) {
2547 Py_DECREF(ret);
2548 ret = NULL;
2549 }
2550 Py_DECREF(next);
2551 Py_DECREF(itlist);
2552 goto Done;
2553 }
2554 PyTuple_SET_ITEM(next, j, item);
2555 }
Tim Peters8572b4f2001-05-06 01:05:02 +00002556
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002557 if (i < len)
2558 PyList_SET_ITEM(ret, i, next);
2559 else {
2560 int status = PyList_Append(ret, next);
2561 Py_DECREF(next);
2562 ++len;
2563 if (status < 0)
2564 goto Fail_ret_itlist;
2565 }
2566 }
Tim Peters8572b4f2001-05-06 01:05:02 +00002567
Tim Peters67d687a2002-04-29 21:27:32 +00002568Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002569 if (ret != NULL && i < len) {
2570 /* The list is too big. */
2571 if (PyList_SetSlice(ret, i, len, NULL) < 0)
2572 return NULL;
2573 }
2574 return ret;
Tim Peters67d687a2002-04-29 21:27:32 +00002575
Tim Peters8572b4f2001-05-06 01:05:02 +00002576Fail_ret_itlist:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002577 Py_DECREF(itlist);
Tim Peters8572b4f2001-05-06 01:05:02 +00002578Fail_ret:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002579 Py_DECREF(ret);
2580 return NULL;
Barry Warsawbd599b52000-08-03 15:45:29 +00002581}
2582
2583
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002584PyDoc_STRVAR(zip_doc,
Barry Warsawbd599b52000-08-03 15:45:29 +00002585"zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2586\n\
2587Return a list of tuples, where each tuple contains the i-th element\n\
2588from each of the argument sequences. The returned list is truncated\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002589in length to the length of the shortest argument sequence.");
Barry Warsawbd599b52000-08-03 15:45:29 +00002590
2591
Guido van Rossum79f25d91997-04-29 20:08:16 +00002592static PyMethodDef builtin_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002593 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2594 {"abs", builtin_abs, METH_O, abs_doc},
2595 {"all", builtin_all, METH_O, all_doc},
2596 {"any", builtin_any, METH_O, any_doc},
2597 {"apply", builtin_apply, METH_VARARGS, apply_doc},
2598 {"bin", builtin_bin, METH_O, bin_doc},
2599 {"callable", builtin_callable, METH_O, callable_doc},
2600 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2601 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
2602 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
2603 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2604 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2605 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2606 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2607 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2608 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
2609 {"filter", builtin_filter, METH_VARARGS, filter_doc},
2610 {"format", builtin_format, METH_VARARGS, format_doc},
2611 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2612 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2613 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2614 {"hash", builtin_hash, METH_O, hash_doc},
2615 {"hex", builtin_hex, METH_O, hex_doc},
2616 {"id", builtin_id, METH_O, id_doc},
2617 {"input", builtin_input, METH_VARARGS, input_doc},
2618 {"intern", builtin_intern, METH_VARARGS, intern_doc},
2619 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2620 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2621 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2622 {"len", builtin_len, METH_O, len_doc},
2623 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2624 {"map", builtin_map, METH_VARARGS, map_doc},
2625 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2626 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2627 {"next", builtin_next, METH_VARARGS, next_doc},
2628 {"oct", builtin_oct, METH_O, oct_doc},
2629 {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
2630 {"ord", builtin_ord, METH_O, ord_doc},
2631 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2632 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2633 {"range", builtin_range, METH_VARARGS, range_doc},
2634 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
2635 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
2636 {"reload", builtin_reload, METH_O, reload_doc},
2637 {"repr", builtin_repr, METH_O, repr_doc},
2638 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2639 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2640 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2641 {"sum", builtin_sum, METH_VARARGS, sum_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002642#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002643 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002644#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002645 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2646 {"zip", builtin_zip, METH_VARARGS, zip_doc},
2647 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002648};
2649
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002650PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002651"Built-in functions, exceptions, and other objects.\n\
2652\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002653Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002654
Guido van Rossum25ce5661997-08-02 03:10:38 +00002655PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002656_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002657{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002658 PyObject *mod, *dict, *debug;
2659 mod = Py_InitModule4("__builtin__", builtin_methods,
2660 builtin_doc, (PyObject *)NULL,
2661 PYTHON_API_VERSION);
2662 if (mod == NULL)
2663 return NULL;
2664 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002665
Tim Peters7571a0f2003-03-23 17:52:28 +00002666#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002667 /* __builtin__ exposes a number of statically allocated objects
2668 * that, before this code was added in 2.3, never showed up in
2669 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2670 * result, programs leaking references to None and False (etc)
2671 * couldn't be diagnosed by examining sys.getobjects(0).
2672 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002673#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2674#else
2675#define ADD_TO_ALL(OBJECT) (void)0
2676#endif
2677
Tim Peters4b7625e2001-09-13 21:37:17 +00002678#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002679 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2680 return NULL; \
2681 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002682
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002683 SETBUILTIN("None", Py_None);
2684 SETBUILTIN("Ellipsis", Py_Ellipsis);
2685 SETBUILTIN("NotImplemented", Py_NotImplemented);
2686 SETBUILTIN("False", Py_False);
2687 SETBUILTIN("True", Py_True);
2688 SETBUILTIN("basestring", &PyBaseString_Type);
2689 SETBUILTIN("bool", &PyBool_Type);
2690 SETBUILTIN("memoryview", &PyMemoryView_Type);
2691 SETBUILTIN("bytearray", &PyByteArray_Type);
2692 SETBUILTIN("bytes", &PyString_Type);
2693 SETBUILTIN("buffer", &PyBuffer_Type);
2694 SETBUILTIN("classmethod", &PyClassMethod_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002695#ifndef WITHOUT_COMPLEX
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002696 SETBUILTIN("complex", &PyComplex_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002697#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002698 SETBUILTIN("dict", &PyDict_Type);
2699 SETBUILTIN("enumerate", &PyEnum_Type);
2700 SETBUILTIN("file", &PyFile_Type);
2701 SETBUILTIN("float", &PyFloat_Type);
2702 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2703 SETBUILTIN("property", &PyProperty_Type);
2704 SETBUILTIN("int", &PyInt_Type);
2705 SETBUILTIN("list", &PyList_Type);
2706 SETBUILTIN("long", &PyLong_Type);
2707 SETBUILTIN("object", &PyBaseObject_Type);
2708 SETBUILTIN("reversed", &PyReversed_Type);
2709 SETBUILTIN("set", &PySet_Type);
2710 SETBUILTIN("slice", &PySlice_Type);
2711 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2712 SETBUILTIN("str", &PyString_Type);
2713 SETBUILTIN("super", &PySuper_Type);
2714 SETBUILTIN("tuple", &PyTuple_Type);
2715 SETBUILTIN("type", &PyType_Type);
2716 SETBUILTIN("xrange", &PyRange_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002717#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002718 SETBUILTIN("unicode", &PyUnicode_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002719#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002720 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2721 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2722 Py_XDECREF(debug);
2723 return NULL;
2724 }
2725 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002726
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002727 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002728#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002729#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002730}
2731
Guido van Rossume77a7571993-11-03 15:01:26 +00002732/* Helper for filter(): filter a tuple through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002733
Guido van Rossum79f25d91997-04-29 20:08:16 +00002734static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002735filtertuple(PyObject *func, PyObject *tuple)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002736{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002737 PyObject *result;
2738 Py_ssize_t i, j;
2739 Py_ssize_t len = PyTuple_Size(tuple);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002740
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002741 if (len == 0) {
2742 if (PyTuple_CheckExact(tuple))
2743 Py_INCREF(tuple);
2744 else
2745 tuple = PyTuple_New(0);
2746 return tuple;
2747 }
Guido van Rossumb7b45621995-08-04 04:07:45 +00002748
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002749 if ((result = PyTuple_New(len)) == NULL)
2750 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002751
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002752 for (i = j = 0; i < len; ++i) {
2753 PyObject *item, *good;
2754 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002755
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002756 if (tuple->ob_type->tp_as_sequence &&
2757 tuple->ob_type->tp_as_sequence->sq_item) {
2758 item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
2759 if (item == NULL)
2760 goto Fail_1;
2761 } else {
2762 PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
2763 goto Fail_1;
2764 }
2765 if (func == Py_None) {
2766 Py_INCREF(item);
2767 good = item;
2768 }
2769 else {
2770 PyObject *arg = PyTuple_Pack(1, item);
2771 if (arg == NULL) {
2772 Py_DECREF(item);
2773 goto Fail_1;
2774 }
2775 good = PyEval_CallObject(func, arg);
2776 Py_DECREF(arg);
2777 if (good == NULL) {
2778 Py_DECREF(item);
2779 goto Fail_1;
2780 }
2781 }
2782 ok = PyObject_IsTrue(good);
2783 Py_DECREF(good);
2784 if (ok) {
2785 if (PyTuple_SetItem(result, j++, item) < 0)
2786 goto Fail_1;
2787 }
2788 else
2789 Py_DECREF(item);
2790 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002791
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002792 if (_PyTuple_Resize(&result, j) < 0)
2793 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002794
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002795 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002796
Guido van Rossum12d12c51993-10-26 17:58:25 +00002797Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002798 Py_DECREF(result);
2799 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002800}
2801
2802
Guido van Rossume77a7571993-11-03 15:01:26 +00002803/* Helper for filter(): filter a string through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002804
Guido van Rossum79f25d91997-04-29 20:08:16 +00002805static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002806filterstring(PyObject *func, PyObject *strobj)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002807{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002808 PyObject *result;
2809 Py_ssize_t i, j;
2810 Py_ssize_t len = PyString_Size(strobj);
2811 Py_ssize_t outlen = len;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002812
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002813 if (func == Py_None) {
2814 /* If it's a real string we can return the original,
2815 * as no character is ever false and __getitem__
2816 * does return this character. If it's a subclass
2817 * we must go through the __getitem__ loop */
2818 if (PyString_CheckExact(strobj)) {
2819 Py_INCREF(strobj);
2820 return strobj;
2821 }
2822 }
2823 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2824 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002825
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002826 for (i = j = 0; i < len; ++i) {
2827 PyObject *item;
2828 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002829
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002830 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2831 if (item == NULL)
2832 goto Fail_1;
2833 if (func==Py_None) {
2834 ok = 1;
2835 } else {
2836 PyObject *arg, *good;
2837 arg = PyTuple_Pack(1, item);
2838 if (arg == NULL) {
2839 Py_DECREF(item);
2840 goto Fail_1;
2841 }
2842 good = PyEval_CallObject(func, arg);
2843 Py_DECREF(arg);
2844 if (good == NULL) {
2845 Py_DECREF(item);
2846 goto Fail_1;
2847 }
2848 ok = PyObject_IsTrue(good);
2849 Py_DECREF(good);
2850 }
2851 if (ok) {
2852 Py_ssize_t reslen;
2853 if (!PyString_Check(item)) {
2854 PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
2855 " __getitem__ returned different type");
2856 Py_DECREF(item);
2857 goto Fail_1;
2858 }
2859 reslen = PyString_GET_SIZE(item);
2860 if (reslen == 1) {
2861 PyString_AS_STRING(result)[j++] =
2862 PyString_AS_STRING(item)[0];
2863 } else {
2864 /* do we need more space? */
2865 Py_ssize_t need = j;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002866
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002867 /* calculate space requirements while checking for overflow */
2868 if (need > PY_SSIZE_T_MAX - reslen) {
2869 Py_DECREF(item);
2870 goto Fail_1;
2871 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002872
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002873 need += reslen;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002874
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002875 if (need > PY_SSIZE_T_MAX - len) {
2876 Py_DECREF(item);
2877 goto Fail_1;
2878 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002879
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002880 need += len;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002881
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002882 if (need <= i) {
2883 Py_DECREF(item);
2884 goto Fail_1;
2885 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002886
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002887 need = need - i - 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002888
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002889 assert(need >= 0);
2890 assert(outlen >= 0);
Gregory P. Smith9d534572008-06-11 07:41:16 +00002891
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002892 if (need > outlen) {
2893 /* overallocate, to avoid reallocations */
2894 if (outlen > PY_SSIZE_T_MAX / 2) {
2895 Py_DECREF(item);
2896 return NULL;
2897 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002898
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002899 if (need<2*outlen) {
2900 need = 2*outlen;
2901 }
2902 if (_PyString_Resize(&result, need)) {
2903 Py_DECREF(item);
2904 return NULL;
2905 }
2906 outlen = need;
2907 }
2908 memcpy(
2909 PyString_AS_STRING(result) + j,
2910 PyString_AS_STRING(item),
2911 reslen
2912 );
2913 j += reslen;
2914 }
2915 }
2916 Py_DECREF(item);
2917 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002918
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002919 if (j < outlen)
2920 _PyString_Resize(&result, j);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002921
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002922 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002923
Guido van Rossum12d12c51993-10-26 17:58:25 +00002924Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002925 Py_DECREF(result);
2926 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002927}
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002928
2929#ifdef Py_USING_UNICODE
2930/* Helper for filter(): filter a Unicode object through a function */
2931
2932static PyObject *
2933filterunicode(PyObject *func, PyObject *strobj)
2934{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002935 PyObject *result;
2936 register Py_ssize_t i, j;
2937 Py_ssize_t len = PyUnicode_GetSize(strobj);
2938 Py_ssize_t outlen = len;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002939
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002940 if (func == Py_None) {
2941 /* If it's a real string we can return the original,
2942 * as no character is ever false and __getitem__
2943 * does return this character. If it's a subclass
2944 * we must go through the __getitem__ loop */
2945 if (PyUnicode_CheckExact(strobj)) {
2946 Py_INCREF(strobj);
2947 return strobj;
2948 }
2949 }
2950 if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
2951 return NULL;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002952
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002953 for (i = j = 0; i < len; ++i) {
2954 PyObject *item, *arg, *good;
2955 int ok;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002956
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002957 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2958 if (item == NULL)
2959 goto Fail_1;
2960 if (func == Py_None) {
2961 ok = 1;
2962 } else {
2963 arg = PyTuple_Pack(1, item);
2964 if (arg == NULL) {
2965 Py_DECREF(item);
2966 goto Fail_1;
2967 }
2968 good = PyEval_CallObject(func, arg);
2969 Py_DECREF(arg);
2970 if (good == NULL) {
2971 Py_DECREF(item);
2972 goto Fail_1;
2973 }
2974 ok = PyObject_IsTrue(good);
2975 Py_DECREF(good);
2976 }
2977 if (ok) {
2978 Py_ssize_t reslen;
2979 if (!PyUnicode_Check(item)) {
2980 PyErr_SetString(PyExc_TypeError,
2981 "can't filter unicode to unicode:"
2982 " __getitem__ returned different type");
2983 Py_DECREF(item);
2984 goto Fail_1;
2985 }
2986 reslen = PyUnicode_GET_SIZE(item);
2987 if (reslen == 1)
2988 PyUnicode_AS_UNICODE(result)[j++] =
2989 PyUnicode_AS_UNICODE(item)[0];
2990 else {
2991 /* do we need more space? */
2992 Py_ssize_t need = j + reslen + len - i - 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002993
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002994 /* check that didnt overflow */
2995 if ((j > PY_SSIZE_T_MAX - reslen) ||
2996 ((j + reslen) > PY_SSIZE_T_MAX - len) ||
2997 ((j + reslen + len) < i) ||
2998 ((j + reslen + len - i) <= 0)) {
2999 Py_DECREF(item);
3000 return NULL;
3001 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00003002
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003003 assert(need >= 0);
3004 assert(outlen >= 0);
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003005
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003006 if (need > outlen) {
3007 /* overallocate,
3008 to avoid reallocations */
3009 if (need < 2 * outlen) {
3010 if (outlen > PY_SSIZE_T_MAX / 2) {
3011 Py_DECREF(item);
3012 return NULL;
3013 } else {
3014 need = 2 * outlen;
3015 }
3016 }
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003017
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003018 if (PyUnicode_Resize(
3019 &result, need) < 0) {
3020 Py_DECREF(item);
3021 goto Fail_1;
3022 }
3023 outlen = need;
3024 }
3025 memcpy(PyUnicode_AS_UNICODE(result) + j,
3026 PyUnicode_AS_UNICODE(item),
3027 reslen*sizeof(Py_UNICODE));
3028 j += reslen;
3029 }
3030 }
3031 Py_DECREF(item);
3032 }
3033
3034 if (j < outlen)
3035 PyUnicode_Resize(&result, j);
3036
3037 return result;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003038
3039Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003040 Py_DECREF(result);
3041 return NULL;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003042}
3043#endif