blob: 373f8706245c8133b64752089a07936a02ee026d [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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000227 return PyBool_FromLong((long)PyCallable_Check(v));
Guido van Rossum2d951851994-08-29 12:52:16 +0000228}
229
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000230PyDoc_STRVAR(callable_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000231"callable(object) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000232\n\
233Return whether the object is callable (i.e., some kind of function).\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000234Note that classes are callable, as are instances with a __call__() method.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000235
236
Guido van Rossum79f25d91997-04-29 20:08:16 +0000237static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000238builtin_filter(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000239{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000240 PyObject *func, *seq, *result, *it, *arg;
241 Py_ssize_t len; /* guess for result list size */
242 register Py_ssize_t j;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000243
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000244 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
245 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000246
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000247 /* Strings and tuples return a result of the same type. */
248 if (PyString_Check(seq))
249 return filterstring(func, seq);
Martin v. Löwis8afd7572003-01-25 22:46:11 +0000250#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000251 if (PyUnicode_Check(seq))
252 return filterunicode(func, seq);
Martin v. Löwis8afd7572003-01-25 22:46:11 +0000253#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000254 if (PyTuple_Check(seq))
255 return filtertuple(func, seq);
Tim Peters0e57abf2001-05-02 07:39:38 +0000256
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000257 /* Pre-allocate argument list tuple. */
258 arg = PyTuple_New(1);
259 if (arg == NULL)
260 return NULL;
Georg Brandle35b6572005-07-19 22:20:20 +0000261
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000262 /* Get iterator. */
263 it = PyObject_GetIter(seq);
264 if (it == NULL)
265 goto Fail_arg;
Tim Peters0e57abf2001-05-02 07:39:38 +0000266
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000267 /* Guess a result list size. */
268 len = _PyObject_LengthHint(seq, 8);
269 if (len == -1)
270 goto Fail_it;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000271
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000272 /* Get a result list. */
273 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
274 /* Eww - can modify the list in-place. */
275 Py_INCREF(seq);
276 result = seq;
277 }
278 else {
279 result = PyList_New(len);
280 if (result == NULL)
281 goto Fail_it;
282 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000283
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000284 /* Build the result list. */
285 j = 0;
286 for (;;) {
287 PyObject *item;
288 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000289
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000290 item = PyIter_Next(it);
291 if (item == NULL) {
292 if (PyErr_Occurred())
293 goto Fail_result_it;
294 break;
295 }
Guido van Rossumdc4b93d1993-10-27 14:56:44 +0000296
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000297 if (func == (PyObject *)&PyBool_Type || func == Py_None) {
298 ok = PyObject_IsTrue(item);
299 }
300 else {
301 PyObject *good;
302 PyTuple_SET_ITEM(arg, 0, item);
303 good = PyObject_Call(func, arg, NULL);
304 PyTuple_SET_ITEM(arg, 0, NULL);
305 if (good == NULL) {
306 Py_DECREF(item);
307 goto Fail_result_it;
308 }
309 ok = PyObject_IsTrue(good);
310 Py_DECREF(good);
311 }
312 if (ok) {
313 if (j < len)
314 PyList_SET_ITEM(result, j, item);
315 else {
316 int status = PyList_Append(result, item);
317 Py_DECREF(item);
318 if (status < 0)
319 goto Fail_result_it;
320 }
321 ++j;
322 }
323 else
324 Py_DECREF(item);
325 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000326
Guido van Rossum12d12c51993-10-26 17:58:25 +0000327
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000328 /* Cut back result list if len is too big. */
329 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
330 goto Fail_result_it;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000331
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000332 Py_DECREF(it);
333 Py_DECREF(arg);
334 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000335
Tim Peters0e57abf2001-05-02 07:39:38 +0000336Fail_result_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000337 Py_DECREF(result);
Tim Peters0e57abf2001-05-02 07:39:38 +0000338Fail_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000339 Py_DECREF(it);
Guido van Rossumc7903a12002-08-16 07:04:56 +0000340Fail_arg:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000341 Py_DECREF(arg);
342 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000343}
344
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000345PyDoc_STRVAR(filter_doc,
Tim Petersd50e5442002-03-09 00:06:26 +0000346"filter(function or None, sequence) -> list, tuple, or string\n"
347"\n"
348"Return those items of sequence for which function(item) is true. If\n"
349"function is None, return the items that are true. If sequence is a tuple\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000350"or string, return the same type, else return a list.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000351
Guido van Rossum79f25d91997-04-29 20:08:16 +0000352static PyObject *
Eric Smitha9f7d622008-02-17 19:46:49 +0000353builtin_format(PyObject *self, PyObject *args)
354{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000355 PyObject *value;
356 PyObject *format_spec = NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +0000357
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000358 if (!PyArg_ParseTuple(args, "O|O:format", &value, &format_spec))
359 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +0000360
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000361 return PyObject_Format(value, format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +0000362}
363
364PyDoc_STRVAR(format_doc,
365"format(value[, format_spec]) -> string\n\
366\n\
367Returns value.__format__(format_spec)\n\
368format_spec defaults to \"\"");
369
370static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000371builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000372{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000373 long x;
374 char s[1];
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000375
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000376 if (!PyArg_ParseTuple(args, "l:chr", &x))
377 return NULL;
378 if (x < 0 || x >= 256) {
379 PyErr_SetString(PyExc_ValueError,
380 "chr() arg not in range(256)");
381 return NULL;
382 }
383 s[0] = (char)x;
384 return PyString_FromStringAndSize(s, 1);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000385}
386
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000387PyDoc_STRVAR(chr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000388"chr(i) -> character\n\
389\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000390Return a string of one character with ordinal i; 0 <= i < 256.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000391
392
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000393#ifdef Py_USING_UNICODE
Guido van Rossum79f25d91997-04-29 20:08:16 +0000394static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000395builtin_unichr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000396{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000397 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000398
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000399 if (!PyArg_ParseTuple(args, "i:unichr", &x))
400 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000401
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000402 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000403}
404
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000405PyDoc_STRVAR(unichr_doc,
Fred Drake078b24f2000-04-13 02:42:50 +0000406"unichr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000407\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000408Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000409#endif
Guido van Rossum09095f32000-03-10 23:00:52 +0000410
411
412static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000413builtin_cmp(PyObject *self, PyObject *args)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000414{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000415 PyObject *a, *b;
416 int c;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000417
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000418 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
419 return NULL;
420 if (PyObject_Cmp(a, b, &c) < 0)
421 return NULL;
422 return PyInt_FromLong((long)c);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000423}
424
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000425PyDoc_STRVAR(cmp_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000426"cmp(x, y) -> integer\n\
427\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000428Return negative if x<y, zero if x==y, positive if x>y.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000429
430
Guido van Rossum79f25d91997-04-29 20:08:16 +0000431static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000432builtin_coerce(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000433{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000434 PyObject *v, *w;
435 PyObject *res;
Guido van Rossum5524a591995-01-10 15:26:20 +0000436
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000437 if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
438 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +0000439
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000440 if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
441 return NULL;
442 if (PyNumber_Coerce(&v, &w) < 0)
443 return NULL;
444 res = PyTuple_Pack(2, v, w);
445 Py_DECREF(v);
446 Py_DECREF(w);
447 return res;
Guido van Rossum04691fc1992-08-12 15:35:34 +0000448}
449
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000450PyDoc_STRVAR(coerce_doc,
Martin v. Löwis8d494f32004-08-25 10:42:41 +0000451"coerce(x, y) -> (x1, y1)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000452\n\
Martin v. Löwis8d494f32004-08-25 10:42:41 +0000453Return a tuple consisting of the two numeric arguments converted to\n\
454a common type, using the same rules as used by arithmetic operations.\n\
455If coercion is not possible, raise TypeError.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000456
Guido van Rossum79f25d91997-04-29 20:08:16 +0000457static PyObject *
Georg Brandl5240d742007-03-13 20:46:32 +0000458builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000459{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000460 char *str;
461 char *filename;
462 char *startstr;
463 int mode = -1;
464 int dont_inherit = 0;
465 int supplied_flags = 0;
466 int is_ast;
467 PyCompilerFlags cf;
468 PyObject *result = NULL, *cmd, *tmp = NULL;
469 Py_ssize_t length;
470 static char *kwlist[] = {"source", "filename", "mode", "flags",
471 "dont_inherit", NULL};
472 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000473
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000474 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
475 kwlist, &cmd, &filename, &startstr,
476 &supplied_flags, &dont_inherit))
477 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000478
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000479 cf.cf_flags = supplied_flags;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000480
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000481 if (supplied_flags &
482 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
483 {
484 PyErr_SetString(PyExc_ValueError,
485 "compile(): unrecognised flags");
486 return NULL;
487 }
488 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Georg Brandlfc8eef32008-03-28 12:11:56 +0000489
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000490 if (!dont_inherit) {
491 PyEval_MergeCompilerFlags(&cf);
492 }
Georg Brandlfc8eef32008-03-28 12:11:56 +0000493
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000494 if (strcmp(startstr, "exec") == 0)
495 mode = 0;
496 else if (strcmp(startstr, "eval") == 0)
497 mode = 1;
498 else if (strcmp(startstr, "single") == 0)
499 mode = 2;
500 else {
501 PyErr_SetString(PyExc_ValueError,
502 "compile() arg 3 must be 'exec', 'eval' or 'single'");
503 return NULL;
504 }
Georg Brandlf2bfd542008-03-29 13:24:23 +0000505
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000506 is_ast = PyAST_Check(cmd);
507 if (is_ast == -1)
508 return NULL;
509 if (is_ast) {
510 if (supplied_flags & PyCF_ONLY_AST) {
511 Py_INCREF(cmd);
512 result = cmd;
513 }
514 else {
515 PyArena *arena;
516 mod_ty mod;
Georg Brandlfc8eef32008-03-28 12:11:56 +0000517
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000518 arena = PyArena_New();
519 mod = PyAST_obj2mod(cmd, arena, mode);
520 if (mod == NULL) {
521 PyArena_Free(arena);
522 return NULL;
523 }
524 result = (PyObject*)PyAST_Compile(mod, filename,
525 &cf, arena);
526 PyArena_Free(arena);
527 }
528 return result;
529 }
Georg Brandlfc8eef32008-03-28 12:11:56 +0000530
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000531#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000532 if (PyUnicode_Check(cmd)) {
533 tmp = PyUnicode_AsUTF8String(cmd);
534 if (tmp == NULL)
535 return NULL;
536 cmd = tmp;
537 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
538 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000539#endif
Tim Peters6cd6a822001-08-17 22:11:27 +0000540
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000541 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))
542 goto cleanup;
543 if ((size_t)length != strlen(str)) {
544 PyErr_SetString(PyExc_TypeError,
545 "compile() expected string without null bytes");
546 goto cleanup;
547 }
548 result = Py_CompileStringFlags(str, filename, start[mode], &cf);
Neal Norwitz3a9a3e72005-11-27 20:38:31 +0000549cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000550 Py_XDECREF(tmp);
551 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000552}
553
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000554PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000555"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000556\n\
557Compile the source string (a Python module, statement or expression)\n\
558into a code object that can be executed by the exec statement or eval().\n\
559The filename will be used for run-time error messages.\n\
560The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000561single (interactive) statement, or 'eval' to compile an expression.\n\
562The flags argument, if present, controls which future statements influence\n\
563the compilation of the code.\n\
564The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
565the effects of any future statements in effect in the code calling\n\
566compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000567in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000568
Guido van Rossum79f25d91997-04-29 20:08:16 +0000569static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000570builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000571{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000572 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000573
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000574 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
575 return NULL;
576 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000577}
578
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000579PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000580"dir([object]) -> list of strings\n"
581"\n"
Georg Brandl871f1bc2007-03-12 13:17:36 +0000582"If called without an argument, return the names in the current scope.\n"
583"Else, return an alphabetized list of names comprising (some of) the attributes\n"
584"of the given object, and of attributes reachable from it.\n"
585"If the object supplies a method named __dir__, it will be used; otherwise\n"
586"the default dir() logic is used and returns:\n"
587" for a module object: the module's attributes.\n"
588" for a class object: its attributes, and recursively the attributes\n"
589" of its bases.\n"
Georg Brandl3bb15672007-03-13 07:23:16 +0000590" for any other object: its attributes, its class's attributes, and\n"
Georg Brandl871f1bc2007-03-12 13:17:36 +0000591" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000592
Guido van Rossum79f25d91997-04-29 20:08:16 +0000593static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000594builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000595{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000596 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000597
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000598 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
599 return NULL;
600 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000601}
602
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000603PyDoc_STRVAR(divmod_doc,
Raymond Hettinger39540a02011-07-19 11:59:20 -0700604"divmod(x, y) -> (quotient, remainder)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000605\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000606Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000607
608
Guido van Rossum79f25d91997-04-29 20:08:16 +0000609static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000610builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000611{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000612 PyObject *cmd, *result, *tmp = NULL;
613 PyObject *globals = Py_None, *locals = Py_None;
614 char *str;
615 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000616
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000617 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
618 return NULL;
619 if (locals != Py_None && !PyMapping_Check(locals)) {
620 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
621 return NULL;
622 }
623 if (globals != Py_None && !PyDict_Check(globals)) {
624 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
625 "globals must be a real dict; try eval(expr, {}, mapping)"
626 : "globals must be a dict");
627 return NULL;
628 }
629 if (globals == Py_None) {
630 globals = PyEval_GetGlobals();
631 if (locals == Py_None)
632 locals = PyEval_GetLocals();
633 }
634 else if (locals == Py_None)
635 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000636
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000637 if (globals == NULL || locals == NULL) {
638 PyErr_SetString(PyExc_TypeError,
639 "eval must be given globals and locals "
640 "when called without a frame");
641 return NULL;
642 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000643
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000644 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
645 if (PyDict_SetItemString(globals, "__builtins__",
646 PyEval_GetBuiltins()) != 0)
647 return NULL;
648 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000649
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000650 if (PyCode_Check(cmd)) {
651 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
652 PyErr_SetString(PyExc_TypeError,
653 "code object passed to eval() may not contain free variables");
654 return NULL;
655 }
656 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
657 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000658
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000659 if (!PyString_Check(cmd) &&
660 !PyUnicode_Check(cmd)) {
661 PyErr_SetString(PyExc_TypeError,
662 "eval() arg 1 must be a string or code object");
663 return NULL;
664 }
665 cf.cf_flags = 0;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000666
667#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000668 if (PyUnicode_Check(cmd)) {
669 tmp = PyUnicode_AsUTF8String(cmd);
670 if (tmp == NULL)
671 return NULL;
672 cmd = tmp;
673 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
674 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000675#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000676 if (PyString_AsStringAndSize(cmd, &str, NULL)) {
677 Py_XDECREF(tmp);
678 return NULL;
679 }
680 while (*str == ' ' || *str == '\t')
681 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000682
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000683 (void)PyEval_MergeCompilerFlags(&cf);
684 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
685 Py_XDECREF(tmp);
686 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000687}
688
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000689PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000690"eval(source[, globals[, locals]]) -> value\n\
691\n\
692Evaluate the source in the context of globals and locals.\n\
693The source may be a string representing a Python expression\n\
694or a code object as returned by compile().\n\
Neal Norwitz477ca1c2006-09-05 02:25:41 +0000695The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000696defaulting to the current globals and locals.\n\
697If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000698
699
Guido van Rossum79f25d91997-04-29 20:08:16 +0000700static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000701builtin_execfile(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000702{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000703 char *filename;
704 PyObject *globals = Py_None, *locals = Py_None;
705 PyObject *res;
706 FILE* fp = NULL;
707 PyCompilerFlags cf;
708 int exists;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000709
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000710 if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
711 1) < 0)
712 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +0000713
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000714 if (!PyArg_ParseTuple(args, "s|O!O:execfile",
715 &filename,
716 &PyDict_Type, &globals,
717 &locals))
718 return NULL;
719 if (locals != Py_None && !PyMapping_Check(locals)) {
720 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
721 return NULL;
722 }
723 if (globals == Py_None) {
724 globals = PyEval_GetGlobals();
725 if (locals == Py_None)
726 locals = PyEval_GetLocals();
727 }
728 else if (locals == Py_None)
729 locals = globals;
730 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
731 if (PyDict_SetItemString(globals, "__builtins__",
732 PyEval_GetBuiltins()) != 0)
733 return NULL;
734 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000735
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000736 exists = 0;
737 /* Test for existence or directory. */
Martin v. Löwis3484a182002-03-09 12:07:51 +0000738#if defined(PLAN9)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000739 {
740 Dir *d;
Martin v. Löwis3484a182002-03-09 12:07:51 +0000741
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000742 if ((d = dirstat(filename))!=nil) {
743 if(d->mode & DMDIR)
744 werrstr("is a directory");
745 else
746 exists = 1;
747 free(d);
748 }
749 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000750#elif defined(RISCOS)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000751 if (object_exists(filename)) {
752 if (isdir(filename))
753 errno = EISDIR;
754 else
755 exists = 1;
756 }
757#else /* standard Posix */
758 {
759 struct stat s;
760 if (stat(filename, &s) == 0) {
761 if (S_ISDIR(s.st_mode))
762# if defined(PYOS_OS2) && defined(PYCC_VACPP)
763 errno = EOS2ERR;
764# else
765 errno = EISDIR;
766# endif
767 else
768 exists = 1;
769 }
770 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000771#endif
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000772
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000773 if (exists) {
774 Py_BEGIN_ALLOW_THREADS
775 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
776 Py_END_ALLOW_THREADS
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000777
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000778 if (fp == NULL) {
779 exists = 0;
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000780 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000781 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000782
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000783 if (!exists) {
784 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
785 return NULL;
786 }
787 cf.cf_flags = 0;
788 if (PyEval_MergeCompilerFlags(&cf))
789 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
790 locals, 1, &cf);
791 else
792 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
793 locals, 1);
794 return res;
Guido van Rossum0f61f8a1992-02-25 18:55:05 +0000795}
796
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000797PyDoc_STRVAR(execfile_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000798"execfile(filename[, globals[, locals]])\n\
799\n\
800Read and execute a Python script from a file.\n\
801The globals and locals are dictionaries, defaulting to the current\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000802globals and locals. If only globals is given, locals defaults to it.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000803
804
Guido van Rossum79f25d91997-04-29 20:08:16 +0000805static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000806builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000807{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000808 PyObject *v, *result, *dflt = NULL;
809 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000810
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000811 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
812 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000813#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000814 if (PyUnicode_Check(name)) {
815 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
816 if (name == NULL)
817 return NULL;
818 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000819#endif
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000820
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000821 if (!PyString_Check(name)) {
822 PyErr_SetString(PyExc_TypeError,
823 "getattr(): attribute name must be string");
824 return NULL;
825 }
826 result = PyObject_GetAttr(v, name);
827 if (result == NULL && dflt != NULL &&
828 PyErr_ExceptionMatches(PyExc_AttributeError))
829 {
830 PyErr_Clear();
831 Py_INCREF(dflt);
832 result = dflt;
833 }
834 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000835}
836
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000837PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000838"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000839\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000840Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
841When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000842exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000843
844
Guido van Rossum79f25d91997-04-29 20:08:16 +0000845static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000846builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000847{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000848 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000849
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000850 d = PyEval_GetGlobals();
851 Py_XINCREF(d);
852 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000853}
854
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000855PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000856"globals() -> dictionary\n\
857\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000858Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000859
860
Guido van Rossum79f25d91997-04-29 20:08:16 +0000861static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000862builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000863{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000864 PyObject *v;
865 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000866
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000867 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
868 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000869#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000870 if (PyUnicode_Check(name)) {
871 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
872 if (name == NULL)
873 return NULL;
874 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000875#endif
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000876
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000877 if (!PyString_Check(name)) {
878 PyErr_SetString(PyExc_TypeError,
879 "hasattr(): attribute name must be string");
880 return NULL;
881 }
882 v = PyObject_GetAttr(v, name);
883 if (v == NULL) {
884 if (!PyErr_ExceptionMatches(PyExc_Exception))
885 return NULL;
886 else {
887 PyErr_Clear();
888 Py_INCREF(Py_False);
889 return Py_False;
890 }
891 }
892 Py_DECREF(v);
893 Py_INCREF(Py_True);
894 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000895}
896
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000897PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000898"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000899\n\
900Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000901(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000902
903
Guido van Rossum79f25d91997-04-29 20:08:16 +0000904static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000905builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000906{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000907 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000908}
909
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000910PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000911"id(object) -> integer\n\
912\n\
913Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000914simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000915
916
Guido van Rossum79f25d91997-04-29 20:08:16 +0000917static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000918builtin_map(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000919{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000920 typedef struct {
921 PyObject *it; /* the iterator object */
922 int saw_StopIteration; /* bool: did the iterator end? */
923 } sequence;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000924
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000925 PyObject *func, *result;
926 sequence *seqs = NULL, *sqp;
927 Py_ssize_t n, len;
928 register int i, j;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000929
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000930 n = PyTuple_Size(args);
931 if (n < 2) {
932 PyErr_SetString(PyExc_TypeError,
933 "map() requires at least two args");
934 return NULL;
935 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000936
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000937 func = PyTuple_GetItem(args, 0);
938 n--;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000939
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000940 if (func == Py_None) {
941 if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
942 "use list(...)", 1) < 0)
943 return NULL;
944 if (n == 1) {
945 /* map(None, S) is the same as list(S). */
946 return PySequence_List(PyTuple_GetItem(args, 1));
947 }
948 }
Guido van Rossumfa4ac711998-07-10 17:37:30 +0000949
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000950 /* Get space for sequence descriptors. Must NULL out the iterator
951 * pointers so that jumping to Fail_2 later doesn't see trash.
952 */
953 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
954 PyErr_NoMemory();
955 return NULL;
956 }
957 for (i = 0; i < n; ++i) {
958 seqs[i].it = (PyObject*)NULL;
959 seqs[i].saw_StopIteration = 0;
960 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000961
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000962 /* Do a first pass to obtain iterators for the arguments, and set len
963 * to the largest of their lengths.
964 */
965 len = 0;
966 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
967 PyObject *curseq;
968 Py_ssize_t curlen;
Guido van Rossumad991772001-01-12 16:03:05 +0000969
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000970 /* Get iterator. */
971 curseq = PyTuple_GetItem(args, i+1);
972 sqp->it = PyObject_GetIter(curseq);
973 if (sqp->it == NULL) {
974 static char errmsg[] =
975 "argument %d to map() must support iteration";
976 char errbuf[sizeof(errmsg) + 25];
977 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
978 PyErr_SetString(PyExc_TypeError, errbuf);
979 goto Fail_2;
980 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000981
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000982 /* Update len. */
983 curlen = _PyObject_LengthHint(curseq, 8);
984 if (curlen > len)
985 len = curlen;
986 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000987
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000988 /* Get space for the result list. */
989 if ((result = (PyObject *) PyList_New(len)) == NULL)
990 goto Fail_2;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000991
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000992 /* Iterate over the sequences until all have stopped. */
993 for (i = 0; ; ++i) {
994 PyObject *alist, *item=NULL, *value;
995 int numactive = 0;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000996
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000997 if (func == Py_None && n == 1)
998 alist = NULL;
999 else if ((alist = PyTuple_New(n)) == NULL)
1000 goto Fail_1;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001001
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001002 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
1003 if (sqp->saw_StopIteration) {
1004 Py_INCREF(Py_None);
1005 item = Py_None;
1006 }
1007 else {
1008 item = PyIter_Next(sqp->it);
1009 if (item)
1010 ++numactive;
1011 else {
1012 if (PyErr_Occurred()) {
1013 Py_XDECREF(alist);
1014 goto Fail_1;
1015 }
1016 Py_INCREF(Py_None);
1017 item = Py_None;
1018 sqp->saw_StopIteration = 1;
1019 }
1020 }
1021 if (alist)
1022 PyTuple_SET_ITEM(alist, j, item);
1023 else
1024 break;
1025 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001026
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001027 if (!alist)
1028 alist = item;
Guido van Rossum2d951851994-08-29 12:52:16 +00001029
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001030 if (numactive == 0) {
1031 Py_DECREF(alist);
1032 break;
1033 }
Guido van Rossum2d951851994-08-29 12:52:16 +00001034
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001035 if (func == Py_None)
1036 value = alist;
1037 else {
1038 value = PyEval_CallObject(func, alist);
1039 Py_DECREF(alist);
1040 if (value == NULL)
1041 goto Fail_1;
1042 }
1043 if (i >= len) {
1044 int status = PyList_Append(result, value);
1045 Py_DECREF(value);
1046 if (status < 0)
1047 goto Fail_1;
1048 }
1049 else if (PyList_SetItem(result, i, value) < 0)
1050 goto Fail_1;
1051 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001052
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001053 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
1054 goto Fail_1;
Guido van Rossumfa4ac711998-07-10 17:37:30 +00001055
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001056 goto Succeed;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001057
Guido van Rossum12d12c51993-10-26 17:58:25 +00001058Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001059 Py_DECREF(result);
Guido van Rossum12d12c51993-10-26 17:58:25 +00001060Fail_2:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001061 result = NULL;
Tim Peters4e9afdc2001-05-03 23:54:49 +00001062Succeed:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001063 assert(seqs);
1064 for (i = 0; i < n; ++i)
1065 Py_XDECREF(seqs[i].it);
1066 PyMem_DEL(seqs);
1067 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001068}
1069
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001070PyDoc_STRVAR(map_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001071"map(function, sequence[, sequence, ...]) -> list\n\
1072\n\
1073Return a list of the results of applying the function to the items of\n\
1074the argument sequence(s). If more than one sequence is given, the\n\
1075function is called with an argument list consisting of the corresponding\n\
1076item of each sequence, substituting None for missing values when not all\n\
1077sequences have the same length. If the function is None, return a list of\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001078the items of the sequence (or a list of tuples if more than one sequence).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001079
1080
Guido van Rossum79f25d91997-04-29 20:08:16 +00001081static PyObject *
Georg Brandl28e08732008-04-30 19:47:09 +00001082builtin_next(PyObject *self, PyObject *args)
1083{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001084 PyObject *it, *res;
1085 PyObject *def = NULL;
Georg Brandl28e08732008-04-30 19:47:09 +00001086
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001087 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1088 return NULL;
1089 if (!PyIter_Check(it)) {
1090 PyErr_Format(PyExc_TypeError,
1091 "%.200s object is not an iterator",
1092 it->ob_type->tp_name);
1093 return NULL;
1094 }
1095
1096 res = (*it->ob_type->tp_iternext)(it);
1097 if (res != NULL) {
1098 return res;
1099 } else if (def != NULL) {
1100 if (PyErr_Occurred()) {
1101 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
1102 return NULL;
1103 PyErr_Clear();
1104 }
1105 Py_INCREF(def);
1106 return def;
1107 } else if (PyErr_Occurred()) {
1108 return NULL;
1109 } else {
1110 PyErr_SetNone(PyExc_StopIteration);
1111 return NULL;
1112 }
Georg Brandl28e08732008-04-30 19:47:09 +00001113}
1114
1115PyDoc_STRVAR(next_doc,
1116"next(iterator[, default])\n\
1117\n\
1118Return the next item from the iterator. If default is given and the iterator\n\
1119is exhausted, it is returned instead of raising StopIteration.");
1120
1121
1122static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001123builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001124{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001125 PyObject *v;
1126 PyObject *name;
1127 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001128
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001129 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1130 return NULL;
1131 if (PyObject_SetAttr(v, name, value) != 0)
1132 return NULL;
1133 Py_INCREF(Py_None);
1134 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001135}
1136
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001137PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001138"setattr(object, name, value)\n\
1139\n\
1140Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001141``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001142
1143
Guido van Rossum79f25d91997-04-29 20:08:16 +00001144static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001145builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001146{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001147 PyObject *v;
1148 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001149
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001150 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1151 return NULL;
1152 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1153 return NULL;
1154 Py_INCREF(Py_None);
1155 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001156}
1157
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001158PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001159"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001160\n\
1161Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001162``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001163
1164
Guido van Rossum79f25d91997-04-29 20:08:16 +00001165static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001166builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001167{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001168 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001169
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001170 x = PyObject_Hash(v);
1171 if (x == -1)
1172 return NULL;
1173 return PyInt_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001174}
1175
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001176PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001177"hash(object) -> integer\n\
1178\n\
1179Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001180the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001181
1182
Guido van Rossum79f25d91997-04-29 20:08:16 +00001183static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001184builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001185{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001186 PyNumberMethods *nb;
1187 PyObject *res;
Benjamin Petersonc6d64ec2008-05-17 20:09:42 +00001188
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001189 if ((nb = v->ob_type->tp_as_number) == NULL ||
1190 nb->nb_hex == NULL) {
1191 PyErr_SetString(PyExc_TypeError,
1192 "hex() argument can't be converted to hex");
1193 return NULL;
1194 }
1195 res = (*nb->nb_hex)(v);
1196 if (res && !PyString_Check(res)) {
1197 PyErr_Format(PyExc_TypeError,
1198 "__hex__ returned non-string (type %.200s)",
1199 res->ob_type->tp_name);
1200 Py_DECREF(res);
1201 return NULL;
1202 }
1203 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001204}
1205
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001206PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001207"hex(number) -> string\n\
1208\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001209Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001210
1211
Tim Petersdbd9ba62000-07-09 03:09:57 +00001212static PyObject *builtin_raw_input(PyObject *, PyObject *);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001213
Guido van Rossum79f25d91997-04-29 20:08:16 +00001214static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001215builtin_input(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001216{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001217 PyObject *line;
1218 char *str;
1219 PyObject *res;
1220 PyObject *globals, *locals;
1221 PyCompilerFlags cf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001222
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001223 line = builtin_raw_input(self, args);
1224 if (line == NULL)
1225 return line;
1226 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1227 return NULL;
1228 while (*str == ' ' || *str == '\t')
1229 str++;
1230 globals = PyEval_GetGlobals();
1231 locals = PyEval_GetLocals();
1232 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1233 if (PyDict_SetItemString(globals, "__builtins__",
1234 PyEval_GetBuiltins()) != 0)
1235 return NULL;
1236 }
1237 cf.cf_flags = 0;
1238 PyEval_MergeCompilerFlags(&cf);
1239 res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1240 Py_DECREF(line);
1241 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001242}
1243
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001244PyDoc_STRVAR(input_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001245"input([prompt]) -> value\n\
1246\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001247Equivalent to eval(raw_input(prompt)).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001248
1249
Guido van Rossume8811f81997-02-14 15:48:05 +00001250static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001251builtin_intern(PyObject *self, PyObject *args)
Guido van Rossume8811f81997-02-14 15:48:05 +00001252{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001253 PyObject *s;
1254 if (!PyArg_ParseTuple(args, "S:intern", &s))
1255 return NULL;
1256 if (!PyString_CheckExact(s)) {
1257 PyErr_SetString(PyExc_TypeError,
1258 "can't intern subclass of string");
1259 return NULL;
1260 }
1261 Py_INCREF(s);
1262 PyString_InternInPlace(&s);
1263 return s;
Guido van Rossume8811f81997-02-14 15:48:05 +00001264}
1265
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001266PyDoc_STRVAR(intern_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001267"intern(string) -> string\n\
1268\n\
1269``Intern'' the given string. This enters the string in the (global)\n\
1270table of interned strings whose purpose is to speed up dictionary lookups.\n\
1271Return the string itself or the previously interned string object with the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001272same value.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001273
1274
Guido van Rossum79f25d91997-04-29 20:08:16 +00001275static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001276builtin_iter(PyObject *self, PyObject *args)
1277{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001278 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001279
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001280 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1281 return NULL;
1282 if (w == NULL)
1283 return PyObject_GetIter(v);
1284 if (!PyCallable_Check(v)) {
1285 PyErr_SetString(PyExc_TypeError,
1286 "iter(v, w): v must be callable");
1287 return NULL;
1288 }
1289 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001290}
1291
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001292PyDoc_STRVAR(iter_doc,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001293"iter(collection) -> iterator\n\
1294iter(callable, sentinel) -> iterator\n\
1295\n\
1296Get an iterator from an object. In the first form, the argument must\n\
1297supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001298In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001299
1300
1301static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001302builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001303{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001304 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001305
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001306 res = PyObject_Size(v);
1307 if (res < 0 && PyErr_Occurred())
1308 return NULL;
1309 return PyInt_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001310}
1311
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001312PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001313"len(object) -> integer\n\
1314\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001315Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001316
1317
Guido van Rossum79f25d91997-04-29 20:08:16 +00001318static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001319builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001320{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001321 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001322
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001323 d = PyEval_GetLocals();
1324 Py_XINCREF(d);
1325 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001326}
1327
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001328PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001329"locals() -> dictionary\n\
1330\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001331Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001332
1333
Guido van Rossum79f25d91997-04-29 20:08:16 +00001334static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001335min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001336{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001337 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1338 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001339
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001340 if (PyTuple_Size(args) > 1)
1341 v = args;
1342 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1343 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001344
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001345 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1346 keyfunc = PyDict_GetItemString(kwds, "key");
1347 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1348 PyErr_Format(PyExc_TypeError,
1349 "%s() got an unexpected keyword argument", name);
1350 return NULL;
1351 }
1352 Py_INCREF(keyfunc);
1353 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001354
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001355 it = PyObject_GetIter(v);
1356 if (it == NULL) {
1357 Py_XDECREF(keyfunc);
1358 return NULL;
1359 }
Tim Petersc3074532001-05-03 07:00:32 +00001360
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001361 maxitem = NULL; /* the result */
1362 maxval = NULL; /* the value associated with the result */
1363 while (( item = PyIter_Next(it) )) {
1364 /* get the value from the key function */
1365 if (keyfunc != NULL) {
1366 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1367 if (val == NULL)
1368 goto Fail_it_item;
1369 }
1370 /* no key function; the value is the item */
1371 else {
1372 val = item;
1373 Py_INCREF(val);
1374 }
Tim Petersc3074532001-05-03 07:00:32 +00001375
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001376 /* maximum value and item are unset; set them */
1377 if (maxval == NULL) {
1378 maxitem = item;
1379 maxval = val;
1380 }
1381 /* maximum value and item are set; update them as necessary */
1382 else {
1383 int cmp = PyObject_RichCompareBool(val, maxval, op);
1384 if (cmp < 0)
1385 goto Fail_it_item_and_val;
1386 else if (cmp > 0) {
1387 Py_DECREF(maxval);
1388 Py_DECREF(maxitem);
1389 maxval = val;
1390 maxitem = item;
1391 }
1392 else {
1393 Py_DECREF(item);
1394 Py_DECREF(val);
1395 }
1396 }
1397 }
1398 if (PyErr_Occurred())
1399 goto Fail_it;
1400 if (maxval == NULL) {
1401 PyErr_Format(PyExc_ValueError,
1402 "%s() arg is an empty sequence", name);
1403 assert(maxitem == NULL);
1404 }
1405 else
1406 Py_DECREF(maxval);
1407 Py_DECREF(it);
1408 Py_XDECREF(keyfunc);
1409 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001410
1411Fail_it_item_and_val:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001412 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001413Fail_it_item:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001414 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001415Fail_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001416 Py_XDECREF(maxval);
1417 Py_XDECREF(maxitem);
1418 Py_DECREF(it);
1419 Py_XDECREF(keyfunc);
1420 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001421}
1422
Guido van Rossum79f25d91997-04-29 20:08:16 +00001423static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001424builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001425{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001426 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001427}
1428
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001429PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001430"min(iterable[, key=func]) -> value\n\
1431min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001432\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001433With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001434With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001435
1436
Guido van Rossum79f25d91997-04-29 20:08:16 +00001437static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001438builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001439{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001440 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001441}
1442
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001443PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001444"max(iterable[, key=func]) -> value\n\
1445max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001446\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001447With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001448With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001449
1450
Guido van Rossum79f25d91997-04-29 20:08:16 +00001451static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001452builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001453{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001454 PyNumberMethods *nb;
1455 PyObject *res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001456
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001457 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1458 nb->nb_oct == NULL) {
1459 PyErr_SetString(PyExc_TypeError,
1460 "oct() argument can't be converted to oct");
1461 return NULL;
1462 }
1463 res = (*nb->nb_oct)(v);
1464 if (res && !PyString_Check(res)) {
1465 PyErr_Format(PyExc_TypeError,
1466 "__oct__ returned non-string (type %.200s)",
1467 res->ob_type->tp_name);
1468 Py_DECREF(res);
1469 return NULL;
1470 }
1471 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001472}
1473
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001474PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001475"oct(number) -> string\n\
1476\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001477Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001478
1479
Guido van Rossum79f25d91997-04-29 20:08:16 +00001480static PyObject *
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001481builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
1482{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001483 return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001484}
1485
1486PyDoc_STRVAR(open_doc,
1487"open(name[, mode[, buffering]]) -> file object\n\
1488\n\
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00001489Open a file using the file() type, returns a file object. This is the\n\
Philip Jenveydd0388a2009-05-28 03:12:16 +00001490preferred way to open a file. See file.__doc__ for further information.");
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001491
1492
1493static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001494builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001495{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001496 long ord;
1497 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001498
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001499 if (PyString_Check(obj)) {
1500 size = PyString_GET_SIZE(obj);
1501 if (size == 1) {
1502 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1503 return PyInt_FromLong(ord);
1504 }
1505 } else if (PyByteArray_Check(obj)) {
1506 size = PyByteArray_GET_SIZE(obj);
1507 if (size == 1) {
1508 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1509 return PyInt_FromLong(ord);
1510 }
Christian Heimes1a6387e2008-03-26 12:49:49 +00001511
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001512#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001513 } else if (PyUnicode_Check(obj)) {
1514 size = PyUnicode_GET_SIZE(obj);
1515 if (size == 1) {
1516 ord = (long)*PyUnicode_AS_UNICODE(obj);
1517 return PyInt_FromLong(ord);
1518 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001519#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001520 } else {
1521 PyErr_Format(PyExc_TypeError,
1522 "ord() expected string of length 1, but " \
1523 "%.200s found", obj->ob_type->tp_name);
1524 return NULL;
1525 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001526
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001527 PyErr_Format(PyExc_TypeError,
1528 "ord() expected a character, "
1529 "but string of length %zd found",
1530 size);
1531 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001532}
1533
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001534PyDoc_STRVAR(ord_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001535"ord(c) -> integer\n\
1536\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001537Return the integer ordinal of a one-character string.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001538
1539
Guido van Rossum79f25d91997-04-29 20:08:16 +00001540static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001541builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001542{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001543 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001544
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001545 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1546 return NULL;
1547 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001548}
1549
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001550PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001551"pow(x, y[, z]) -> number\n\
1552\n\
1553With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001554equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001555
1556
Eric Smith7c478942008-03-18 23:45:49 +00001557static PyObject *
1558builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1559{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001560 static char *kwlist[] = {"sep", "end", "file", 0};
1561 static PyObject *dummy_args = NULL;
1562 static PyObject *unicode_newline = NULL, *unicode_space = NULL;
1563 static PyObject *str_newline = NULL, *str_space = NULL;
1564 PyObject *newline, *space;
1565 PyObject *sep = NULL, *end = NULL, *file = NULL;
1566 int i, err, use_unicode = 0;
Eric Smith7c478942008-03-18 23:45:49 +00001567
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001568 if (dummy_args == NULL) {
1569 if (!(dummy_args = PyTuple_New(0)))
1570 return NULL;
1571 }
1572 if (str_newline == NULL) {
1573 str_newline = PyString_FromString("\n");
1574 if (str_newline == NULL)
1575 return NULL;
1576 str_space = PyString_FromString(" ");
1577 if (str_space == NULL) {
1578 Py_CLEAR(str_newline);
1579 return NULL;
1580 }
Martin v. Löwised11a5d2012-05-20 10:42:17 +02001581#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001582 unicode_newline = PyUnicode_FromString("\n");
1583 if (unicode_newline == NULL) {
1584 Py_CLEAR(str_newline);
1585 Py_CLEAR(str_space);
1586 return NULL;
1587 }
1588 unicode_space = PyUnicode_FromString(" ");
1589 if (unicode_space == NULL) {
1590 Py_CLEAR(str_newline);
1591 Py_CLEAR(str_space);
1592 Py_CLEAR(unicode_space);
1593 return NULL;
1594 }
Martin v. Löwised11a5d2012-05-20 10:42:17 +02001595#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001596 }
1597 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1598 kwlist, &sep, &end, &file))
1599 return NULL;
1600 if (file == NULL || file == Py_None) {
1601 file = PySys_GetObject("stdout");
1602 /* sys.stdout may be None when FILE* stdout isn't connected */
1603 if (file == Py_None)
1604 Py_RETURN_NONE;
1605 }
1606 if (sep == Py_None) {
1607 sep = NULL;
1608 }
1609 else if (sep) {
1610 if (PyUnicode_Check(sep)) {
1611 use_unicode = 1;
1612 }
1613 else if (!PyString_Check(sep)) {
1614 PyErr_Format(PyExc_TypeError,
1615 "sep must be None, str or unicode, not %.200s",
1616 sep->ob_type->tp_name);
1617 return NULL;
1618 }
1619 }
1620 if (end == Py_None)
1621 end = NULL;
1622 else if (end) {
1623 if (PyUnicode_Check(end)) {
1624 use_unicode = 1;
1625 }
1626 else if (!PyString_Check(end)) {
1627 PyErr_Format(PyExc_TypeError,
1628 "end must be None, str or unicode, not %.200s",
1629 end->ob_type->tp_name);
1630 return NULL;
1631 }
1632 }
Benjamin Peterson753d1622009-07-02 18:16:45 +00001633
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001634 if (!use_unicode) {
1635 for (i = 0; i < PyTuple_Size(args); i++) {
1636 if (PyUnicode_Check(PyTuple_GET_ITEM(args, i))) {
1637 use_unicode = 1;
1638 break;
1639 }
1640 }
1641 }
1642 if (use_unicode) {
1643 newline = unicode_newline;
1644 space = unicode_space;
1645 }
1646 else {
1647 newline = str_newline;
1648 space = str_space;
1649 }
Eric Smith7c478942008-03-18 23:45:49 +00001650
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001651 for (i = 0; i < PyTuple_Size(args); i++) {
1652 if (i > 0) {
1653 if (sep == NULL)
1654 err = PyFile_WriteObject(space, file,
1655 Py_PRINT_RAW);
1656 else
1657 err = PyFile_WriteObject(sep, file,
1658 Py_PRINT_RAW);
1659 if (err)
1660 return NULL;
1661 }
1662 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1663 Py_PRINT_RAW);
1664 if (err)
1665 return NULL;
1666 }
Eric Smith7c478942008-03-18 23:45:49 +00001667
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001668 if (end == NULL)
1669 err = PyFile_WriteObject(newline, file, Py_PRINT_RAW);
1670 else
1671 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1672 if (err)
1673 return NULL;
Eric Smith7c478942008-03-18 23:45:49 +00001674
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001675 Py_RETURN_NONE;
Eric Smith7c478942008-03-18 23:45:49 +00001676}
1677
1678PyDoc_STRVAR(print_doc,
1679"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
1680\n\
1681Prints the values to a stream, or to sys.stdout by default.\n\
1682Optional keyword arguments:\n\
1683file: a file-like object (stream); defaults to the current sys.stdout.\n\
1684sep: string inserted between values, default a space.\n\
1685end: string appended after the last value, default a newline.");
1686
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001687
1688/* Return number of items in range (lo, hi, step), when arguments are
1689 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1690 * & only if the true value is too large to fit in a signed long.
1691 * Arguments MUST return 1 with either PyInt_Check() or
1692 * PyLong_Check(). Return -1 when there is an error.
1693 */
1694static long
1695get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
1696{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001697 /* -------------------------------------------------------------
1698 Algorithm is equal to that of get_len_of_range(), but it operates
1699 on PyObjects (which are assumed to be PyLong or PyInt objects).
1700 ---------------------------------------------------------------*/
1701 long n;
1702 PyObject *diff = NULL;
1703 PyObject *one = NULL;
1704 PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
1705 /* holds sub-expression evaluations */
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001706
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001707 /* if (lo >= hi), return length of 0. */
1708 if (PyObject_Compare(lo, hi) >= 0)
1709 return 0;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001710
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001711 if ((one = PyLong_FromLong(1L)) == NULL)
1712 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001713
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001714 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
1715 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001716
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001717 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
1718 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001719
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001720 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
1721 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001722
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001723 if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
1724 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001725
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001726 n = PyLong_AsLong(tmp3);
1727 if (PyErr_Occurred()) { /* Check for Overflow */
1728 PyErr_Clear();
1729 goto Fail;
1730 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001731
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001732 Py_DECREF(tmp3);
1733 Py_DECREF(tmp2);
1734 Py_DECREF(diff);
1735 Py_DECREF(tmp1);
1736 Py_DECREF(one);
1737 return n;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001738
1739 Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001740 Py_XDECREF(tmp3);
1741 Py_XDECREF(tmp2);
1742 Py_XDECREF(diff);
1743 Py_XDECREF(tmp1);
1744 Py_XDECREF(one);
1745 return -1;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001746}
1747
Mark Dickinsona8d26682010-05-04 16:18:25 +00001748/* Helper function for handle_range_longs. If arg is int or long
1749 object, returns it with incremented reference count. If arg is
1750 float, raises type error. As a last resort, creates a new int by
1751 calling arg type's nb_int method if it is defined. Returns NULL
1752 and sets exception on error.
1753
1754 Returns a new reference to an int object. */
1755static PyObject *
1756get_range_long_argument(PyObject *arg, const char *name)
1757{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001758 PyObject *v;
1759 PyNumberMethods *nb;
1760 if (PyInt_Check(arg) || PyLong_Check(arg)) {
1761 Py_INCREF(arg);
1762 return arg;
1763 }
1764 if (PyFloat_Check(arg) ||
1765 (nb = Py_TYPE(arg)->tp_as_number) == NULL ||
1766 nb->nb_int == NULL) {
1767 PyErr_Format(PyExc_TypeError,
1768 "range() integer %s argument expected, got %s.",
1769 name, arg->ob_type->tp_name);
1770 return NULL;
1771 }
1772 v = nb->nb_int(arg);
1773 if (v == NULL)
1774 return NULL;
1775 if (PyInt_Check(v) || PyLong_Check(v))
1776 return v;
1777 Py_DECREF(v);
1778 PyErr_SetString(PyExc_TypeError,
1779 "__int__ should return int object");
1780 return NULL;
Mark Dickinsona8d26682010-05-04 16:18:25 +00001781}
1782
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001783/* An extension of builtin_range() that handles the case when PyLong
1784 * arguments are given. */
1785static PyObject *
Mark Dickinsonef9b4ab2010-05-04 16:19:06 +00001786handle_range_longs(PyObject *self, PyObject *args)
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001787{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001788 PyObject *ilow = NULL;
1789 PyObject *ihigh = NULL;
1790 PyObject *istep = NULL;
Tim Peters874e1f72003-04-13 22:13:08 +00001791
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001792 PyObject *low = NULL;
1793 PyObject *high = NULL;
1794 PyObject *step = NULL;
Mark Dickinsona8d26682010-05-04 16:18:25 +00001795
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001796 PyObject *curnum = NULL;
1797 PyObject *v = NULL;
1798 long bign;
1799 Py_ssize_t i, n;
1800 int cmp_result;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001801
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001802 PyObject *zero = PyLong_FromLong(0);
Tim Peters874e1f72003-04-13 22:13:08 +00001803
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001804 if (zero == NULL)
1805 return NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001806
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001807 if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
1808 Py_DECREF(zero);
1809 return NULL;
1810 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001811
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001812 /* Figure out which way we were called, supply defaults, and be
1813 * sure to incref everything so that the decrefs at the end
1814 * are correct. NB: ilow, ihigh and istep are borrowed references.
1815 */
1816 assert(ilow != NULL);
1817 if (ihigh == NULL) {
1818 /* only 1 arg -- it's the upper limit */
1819 ihigh = ilow;
1820 ilow = NULL;
1821 }
Mark Dickinsona8d26682010-05-04 16:18:25 +00001822
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001823 /* convert ihigh if necessary */
1824 assert(ihigh != NULL);
1825 high = get_range_long_argument(ihigh, "end");
1826 if (high == NULL)
1827 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001828
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001829 /* ihigh correct now; do ilow */
1830 if (ilow == NULL) {
1831 Py_INCREF(zero);
1832 low = zero;
1833 }
1834 else {
1835 low = get_range_long_argument(ilow, "start");
1836 if (low == NULL)
1837 goto Fail;
1838 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001839
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001840 /* ilow and ihigh correct now; do istep */
1841 if (istep == NULL)
1842 step = PyLong_FromLong(1);
1843 else
1844 step = get_range_long_argument(istep, "step");
1845 if (step == NULL)
1846 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001847
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001848 if (PyObject_Cmp(step, zero, &cmp_result) == -1)
1849 goto Fail;
Tim Peters874e1f72003-04-13 22:13:08 +00001850
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001851 if (cmp_result == 0) {
1852 PyErr_SetString(PyExc_ValueError,
1853 "range() step argument must not be zero");
1854 goto Fail;
1855 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001856
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001857 if (cmp_result > 0)
1858 bign = get_len_of_range_longs(low, high, step);
1859 else {
1860 PyObject *neg_step = PyNumber_Negative(step);
1861 if (neg_step == NULL)
1862 goto Fail;
1863 bign = get_len_of_range_longs(high, low, neg_step);
1864 Py_DECREF(neg_step);
1865 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001866
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001867 n = (Py_ssize_t)bign;
1868 if (bign < 0 || (long)n != bign) {
1869 PyErr_SetString(PyExc_OverflowError,
1870 "range() result has too many items");
1871 goto Fail;
1872 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001873
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001874 v = PyList_New(n);
1875 if (v == NULL)
1876 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001877
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001878 curnum = low;
1879 Py_INCREF(curnum);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001880
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001881 for (i = 0; i < n; i++) {
1882 PyObject *w = PyNumber_Long(curnum);
1883 PyObject *tmp_num;
1884 if (w == NULL)
1885 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001886
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001887 PyList_SET_ITEM(v, i, w);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001888
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001889 tmp_num = PyNumber_Add(curnum, step);
1890 if (tmp_num == NULL)
1891 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001892
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001893 Py_DECREF(curnum);
1894 curnum = tmp_num;
1895 }
1896 Py_DECREF(low);
1897 Py_DECREF(high);
1898 Py_DECREF(step);
1899 Py_DECREF(zero);
1900 Py_DECREF(curnum);
1901 return v;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001902
1903 Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001904 Py_XDECREF(low);
1905 Py_XDECREF(high);
1906 Py_XDECREF(step);
1907 Py_DECREF(zero);
1908 Py_XDECREF(curnum);
1909 Py_XDECREF(v);
1910 return NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001911}
1912
Guido van Rossum124eff01999-02-23 16:11:01 +00001913/* Return number of items in range/xrange (lo, hi, step). step > 0
1914 * required. Return a value < 0 if & only if the true value is too
1915 * large to fit in a signed long.
1916 */
1917static long
Thomas Wouterse28c2962000-07-23 22:21:32 +00001918get_len_of_range(long lo, long hi, long step)
Guido van Rossum124eff01999-02-23 16:11:01 +00001919{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001920 /* -------------------------------------------------------------
1921 If lo >= hi, the range is empty.
1922 Else if n values are in the range, the last one is
1923 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1924 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1925 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1926 the RHS is non-negative and so truncation is the same as the
1927 floor. Letting M be the largest positive long, the worst case
1928 for the RHS numerator is hi=M, lo=-M-1, and then
1929 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1930 precision to compute the RHS exactly.
1931 ---------------------------------------------------------------*/
1932 long n = 0;
1933 if (lo < hi) {
1934 unsigned long uhi = (unsigned long)hi;
1935 unsigned long ulo = (unsigned long)lo;
1936 unsigned long diff = uhi - ulo - 1;
1937 n = (long)(diff / (unsigned long)step + 1);
1938 }
1939 return n;
Guido van Rossum124eff01999-02-23 16:11:01 +00001940}
1941
Guido van Rossum79f25d91997-04-29 20:08:16 +00001942static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001943builtin_range(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001944{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001945 long ilow = 0, ihigh = 0, istep = 1;
1946 long bign;
1947 Py_ssize_t i, n;
Guido van Rossum124eff01999-02-23 16:11:01 +00001948
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001949 PyObject *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001950
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001951 if (PyTuple_Size(args) <= 1) {
1952 if (!PyArg_ParseTuple(args,
1953 "l;range() requires 1-3 int arguments",
1954 &ihigh)) {
1955 PyErr_Clear();
1956 return handle_range_longs(self, args);
1957 }
1958 }
1959 else {
1960 if (!PyArg_ParseTuple(args,
1961 "ll|l;range() requires 1-3 int arguments",
1962 &ilow, &ihigh, &istep)) {
1963 PyErr_Clear();
1964 return handle_range_longs(self, args);
1965 }
1966 }
1967 if (istep == 0) {
1968 PyErr_SetString(PyExc_ValueError,
1969 "range() step argument must not be zero");
1970 return NULL;
1971 }
1972 if (istep > 0)
1973 bign = get_len_of_range(ilow, ihigh, istep);
1974 else
1975 bign = get_len_of_range(ihigh, ilow, -istep);
1976 n = (Py_ssize_t)bign;
1977 if (bign < 0 || (long)n != bign) {
1978 PyErr_SetString(PyExc_OverflowError,
1979 "range() result has too many items");
1980 return NULL;
1981 }
1982 v = PyList_New(n);
1983 if (v == NULL)
1984 return NULL;
1985 for (i = 0; i < n; i++) {
1986 PyObject *w = PyInt_FromLong(ilow);
1987 if (w == NULL) {
1988 Py_DECREF(v);
1989 return NULL;
1990 }
1991 PyList_SET_ITEM(v, i, w);
1992 ilow += istep;
1993 }
1994 return v;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001995}
1996
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001997PyDoc_STRVAR(range_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001998"range([start,] stop[, step]) -> list of integers\n\
1999\n\
2000Return a list containing an arithmetic progression of integers.\n\
2001range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
2002When step is given, it specifies the increment (or decrement).\n\
2003For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002004These are exactly the valid indices for a list of 4 elements.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002005
2006
Guido van Rossum79f25d91997-04-29 20:08:16 +00002007static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002008builtin_raw_input(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002009{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002010 PyObject *v = NULL;
2011 PyObject *fin = PySys_GetObject("stdin");
2012 PyObject *fout = PySys_GetObject("stdout");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002013
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002014 if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
2015 return NULL;
Martin v. Löwis31d2df52002-08-14 15:46:02 +00002016
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002017 if (fin == NULL) {
2018 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
2019 return NULL;
2020 }
2021 if (fout == NULL) {
2022 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
2023 return NULL;
2024 }
2025 if (PyFile_SoftSpace(fout, 0)) {
2026 if (PyFile_WriteString(" ", fout) != 0)
2027 return NULL;
2028 }
2029 if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
2030 && isatty(fileno(PyFile_AsFile(fin)))
2031 && isatty(fileno(PyFile_AsFile(fout)))) {
2032 PyObject *po;
2033 char *prompt;
2034 char *s;
2035 PyObject *result;
2036 if (v != NULL) {
2037 po = PyObject_Str(v);
2038 if (po == NULL)
2039 return NULL;
2040 prompt = PyString_AsString(po);
2041 if (prompt == NULL)
2042 return NULL;
2043 }
2044 else {
2045 po = NULL;
2046 prompt = "";
2047 }
2048 s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
2049 prompt);
2050 Py_XDECREF(po);
2051 if (s == NULL) {
2052 if (!PyErr_Occurred())
2053 PyErr_SetNone(PyExc_KeyboardInterrupt);
2054 return NULL;
2055 }
2056 if (*s == '\0') {
2057 PyErr_SetNone(PyExc_EOFError);
2058 result = NULL;
2059 }
2060 else { /* strip trailing '\n' */
2061 size_t len = strlen(s);
2062 if (len > PY_SSIZE_T_MAX) {
2063 PyErr_SetString(PyExc_OverflowError,
2064 "[raw_]input: input too long");
2065 result = NULL;
2066 }
2067 else {
2068 result = PyString_FromStringAndSize(s, len-1);
2069 }
2070 }
2071 PyMem_FREE(s);
2072 return result;
2073 }
2074 if (v != NULL) {
2075 if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
2076 return NULL;
2077 }
2078 return PyFile_GetLine(fin, -1);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002079}
2080
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002081PyDoc_STRVAR(raw_input_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002082"raw_input([prompt]) -> string\n\
2083\n\
2084Read a string from standard input. The trailing newline is stripped.\n\
2085If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
2086On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002087is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002088
2089
Guido van Rossum79f25d91997-04-29 20:08:16 +00002090static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002091builtin_reduce(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002092{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002093 static PyObject *functools_reduce = NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002094
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002095 if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
2096 "use functools.reduce()", 1) < 0)
2097 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +00002098
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002099 if (functools_reduce == NULL) {
2100 PyObject *functools = PyImport_ImportModule("functools");
2101 if (functools == NULL)
2102 return NULL;
2103 functools_reduce = PyObject_GetAttrString(functools, "reduce");
2104 Py_DECREF(functools);
2105 if (functools_reduce == NULL)
2106 return NULL;
2107 }
2108 return PyObject_Call(functools_reduce, args, NULL);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002109}
2110
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002111PyDoc_STRVAR(reduce_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002112"reduce(function, sequence[, initial]) -> value\n\
2113\n\
2114Apply a function of two arguments cumulatively to the items of a sequence,\n\
2115from left to right, so as to reduce the sequence to a single value.\n\
2116For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
2117((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
2118of the sequence in the calculation, and serves as a default when the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002119sequence is empty.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002120
2121
Guido van Rossum79f25d91997-04-29 20:08:16 +00002122static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002123builtin_reload(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002124{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002125 if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
2126 1) < 0)
2127 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +00002128
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002129 return PyImport_ReloadModule(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002130}
2131
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002132PyDoc_STRVAR(reload_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002133"reload(module) -> module\n\
2134\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002135Reload the module. The module must have been successfully imported before.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002136
2137
Guido van Rossum79f25d91997-04-29 20:08:16 +00002138static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002139builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00002140{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002141 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002142}
2143
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002144PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002145"repr(object) -> string\n\
2146\n\
2147Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002148For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002149
2150
Guido van Rossum79f25d91997-04-29 20:08:16 +00002151static PyObject *
Georg Brandlccadf842006-03-31 18:54:53 +00002152builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002153{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002154 double x;
2155 PyObject *o_ndigits = NULL;
2156 Py_ssize_t ndigits;
2157 static char *kwlist[] = {"number", "ndigits", 0};
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002158
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002159 if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|O:round",
2160 kwlist, &x, &o_ndigits))
2161 return NULL;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002162
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002163 if (o_ndigits == NULL) {
2164 /* second argument defaults to 0 */
2165 ndigits = 0;
2166 }
2167 else {
2168 /* interpret 2nd argument as a Py_ssize_t; clip on overflow */
2169 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
2170 if (ndigits == -1 && PyErr_Occurred())
2171 return NULL;
2172 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002173
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002174 /* nans, infinities and zeros round to themselves */
2175 if (!Py_IS_FINITE(x) || x == 0.0)
2176 return PyFloat_FromDouble(x);
Mark Dickinsonbce78372009-11-24 10:54:58 +00002177
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002178 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
2179 always rounds to itself. For ndigits < NDIGITS_MIN, x always
2180 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002181#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
2182#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002183 if (ndigits > NDIGITS_MAX)
2184 /* return x */
2185 return PyFloat_FromDouble(x);
2186 else if (ndigits < NDIGITS_MIN)
2187 /* return 0.0, but with sign of x */
2188 return PyFloat_FromDouble(0.0*x);
2189 else
2190 /* finite x, and ndigits is not unreasonably large */
2191 /* _Py_double_round is defined in floatobject.c */
2192 return _Py_double_round(x, (int)ndigits);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002193#undef NDIGITS_MAX
2194#undef NDIGITS_MIN
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002195}
2196
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002197PyDoc_STRVAR(round_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002198"round(number[, ndigits]) -> floating point number\n\
2199\n\
2200Round a number to a given precision in decimal digits (default 0 digits).\n\
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +00002201This always returns a floating point number. Precision may be negative.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002202
Raymond Hettinger64958a12003-12-17 20:43:33 +00002203static PyObject *
2204builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2205{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002206 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
2207 PyObject *callable;
2208 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
2209 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002210
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002211 /* args 1-4 should match listsort in Objects/listobject.c */
2212 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
2213 kwlist, &seq, &compare, &keyfunc, &reverse))
2214 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002215
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002216 newlist = PySequence_List(seq);
2217 if (newlist == NULL)
2218 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002219
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002220 callable = PyObject_GetAttrString(newlist, "sort");
2221 if (callable == NULL) {
2222 Py_DECREF(newlist);
2223 return NULL;
2224 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002225
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002226 newargs = PyTuple_GetSlice(args, 1, 4);
2227 if (newargs == NULL) {
2228 Py_DECREF(newlist);
2229 Py_DECREF(callable);
2230 return NULL;
2231 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00002232
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002233 v = PyObject_Call(callable, newargs, kwds);
2234 Py_DECREF(newargs);
2235 Py_DECREF(callable);
2236 if (v == NULL) {
2237 Py_DECREF(newlist);
2238 return NULL;
2239 }
2240 Py_DECREF(v);
2241 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002242}
2243
2244PyDoc_STRVAR(sorted_doc,
2245"sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002246
Guido van Rossum79f25d91997-04-29 20:08:16 +00002247static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002248builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002249{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002250 PyObject *v = NULL;
2251 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002252
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002253 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2254 return NULL;
2255 if (v == NULL) {
2256 d = PyEval_GetLocals();
2257 if (d == NULL) {
2258 if (!PyErr_Occurred())
2259 PyErr_SetString(PyExc_SystemError,
2260 "vars(): no locals!?");
2261 }
2262 else
2263 Py_INCREF(d);
2264 }
2265 else {
2266 d = PyObject_GetAttrString(v, "__dict__");
2267 if (d == NULL) {
2268 PyErr_SetString(PyExc_TypeError,
2269 "vars() argument must have __dict__ attribute");
2270 return NULL;
2271 }
2272 }
2273 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002274}
2275
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002276PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002277"vars([object]) -> dictionary\n\
2278\n\
2279Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002280With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002281
Alex Martellia70b1912003-04-22 08:12:33 +00002282
2283static PyObject*
2284builtin_sum(PyObject *self, PyObject *args)
2285{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002286 PyObject *seq;
2287 PyObject *result = NULL;
2288 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002289
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002290 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
2291 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002292
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002293 iter = PyObject_GetIter(seq);
2294 if (iter == NULL)
2295 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002296
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002297 if (result == NULL) {
2298 result = PyInt_FromLong(0);
2299 if (result == NULL) {
2300 Py_DECREF(iter);
2301 return NULL;
2302 }
2303 } else {
2304 /* reject string values for 'start' parameter */
2305 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
2306 PyErr_SetString(PyExc_TypeError,
2307 "sum() can't sum strings [use ''.join(seq) instead]");
2308 Py_DECREF(iter);
2309 return NULL;
2310 }
2311 Py_INCREF(result);
2312 }
Alex Martellia70b1912003-04-22 08:12:33 +00002313
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002314#ifndef SLOW_SUM
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002315 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2316 Assumes all inputs are the same type. If the assumption fails, default
2317 to the more general routine.
2318 */
2319 if (PyInt_CheckExact(result)) {
2320 long i_result = PyInt_AS_LONG(result);
2321 Py_DECREF(result);
2322 result = NULL;
2323 while(result == NULL) {
2324 item = PyIter_Next(iter);
2325 if (item == NULL) {
2326 Py_DECREF(iter);
2327 if (PyErr_Occurred())
2328 return NULL;
2329 return PyInt_FromLong(i_result);
2330 }
2331 if (PyInt_CheckExact(item)) {
2332 long b = PyInt_AS_LONG(item);
2333 long x = i_result + b;
2334 if ((x^i_result) >= 0 || (x^b) >= 0) {
2335 i_result = x;
2336 Py_DECREF(item);
2337 continue;
2338 }
2339 }
2340 /* Either overflowed or is not an int. Restore real objects and process normally */
2341 result = PyInt_FromLong(i_result);
2342 temp = PyNumber_Add(result, item);
2343 Py_DECREF(result);
2344 Py_DECREF(item);
2345 result = temp;
2346 if (result == NULL) {
2347 Py_DECREF(iter);
2348 return NULL;
2349 }
2350 }
2351 }
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002352
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002353 if (PyFloat_CheckExact(result)) {
2354 double f_result = PyFloat_AS_DOUBLE(result);
2355 Py_DECREF(result);
2356 result = NULL;
2357 while(result == NULL) {
2358 item = PyIter_Next(iter);
2359 if (item == NULL) {
2360 Py_DECREF(iter);
2361 if (PyErr_Occurred())
2362 return NULL;
2363 return PyFloat_FromDouble(f_result);
2364 }
2365 if (PyFloat_CheckExact(item)) {
2366 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2367 f_result += PyFloat_AS_DOUBLE(item);
2368 PyFPE_END_PROTECT(f_result)
2369 Py_DECREF(item);
2370 continue;
2371 }
2372 if (PyInt_CheckExact(item)) {
2373 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2374 f_result += (double)PyInt_AS_LONG(item);
2375 PyFPE_END_PROTECT(f_result)
2376 Py_DECREF(item);
2377 continue;
2378 }
2379 result = PyFloat_FromDouble(f_result);
2380 temp = PyNumber_Add(result, item);
2381 Py_DECREF(result);
2382 Py_DECREF(item);
2383 result = temp;
2384 if (result == NULL) {
2385 Py_DECREF(iter);
2386 return NULL;
2387 }
2388 }
2389 }
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002390#endif
2391
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002392 for(;;) {
2393 item = PyIter_Next(iter);
2394 if (item == NULL) {
2395 /* error, or end-of-sequence */
2396 if (PyErr_Occurred()) {
2397 Py_DECREF(result);
2398 result = NULL;
2399 }
2400 break;
2401 }
2402 /* It's tempting to use PyNumber_InPlaceAdd instead of
2403 PyNumber_Add here, to avoid quadratic running time
2404 when doing 'sum(list_of_lists, [])'. However, this
2405 would produce a change in behaviour: a snippet like
Mark Dickinson0e0e2152009-10-26 14:18:44 +00002406
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002407 empty = []
2408 sum([[x] for x in range(10)], empty)
Mark Dickinson0e0e2152009-10-26 14:18:44 +00002409
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002410 would change the value of empty. */
2411 temp = PyNumber_Add(result, item);
2412 Py_DECREF(result);
2413 Py_DECREF(item);
2414 result = temp;
2415 if (result == NULL)
2416 break;
2417 }
2418 Py_DECREF(iter);
2419 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002420}
2421
2422PyDoc_STRVAR(sum_doc,
Georg Brandl8134d062006-10-12 12:33:07 +00002423"sum(sequence[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002424\n\
2425Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
Georg Brandl8134d062006-10-12 12:33:07 +00002426of parameter 'start' (which defaults to 0). When the sequence is\n\
2427empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002428
2429
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002430static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002431builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002432{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002433 PyObject *inst;
2434 PyObject *cls;
2435 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002436
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002437 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2438 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002439
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002440 retval = PyObject_IsInstance(inst, cls);
2441 if (retval < 0)
2442 return NULL;
2443 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002444}
2445
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002446PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002447"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002448\n\
2449Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002450With a type as second argument, return whether that is the object's type.\n\
2451The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002452isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002453
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002454
2455static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002456builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002457{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002458 PyObject *derived;
2459 PyObject *cls;
2460 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002461
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002462 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2463 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002464
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002465 retval = PyObject_IsSubclass(derived, cls);
2466 if (retval < 0)
2467 return NULL;
2468 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002469}
2470
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002471PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002472"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002473\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002474Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2475When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2476is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002477
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002478
Barry Warsawbd599b52000-08-03 15:45:29 +00002479static PyObject*
2480builtin_zip(PyObject *self, PyObject *args)
2481{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002482 PyObject *ret;
2483 const Py_ssize_t itemsize = PySequence_Length(args);
2484 Py_ssize_t i;
2485 PyObject *itlist; /* tuple of iterators */
2486 Py_ssize_t len; /* guess at result length */
Barry Warsawbd599b52000-08-03 15:45:29 +00002487
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002488 if (itemsize == 0)
2489 return PyList_New(0);
Raymond Hettingereaef6152003-08-02 07:42:57 +00002490
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002491 /* args must be a tuple */
2492 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002493
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002494 /* Guess at result length: the shortest of the input lengths.
2495 If some argument refuses to say, we refuse to guess too, lest
2496 an argument like xrange(sys.maxint) lead us astray.*/
2497 len = -1; /* unknown */
2498 for (i = 0; i < itemsize; ++i) {
2499 PyObject *item = PyTuple_GET_ITEM(args, i);
2500 Py_ssize_t thislen = _PyObject_LengthHint(item, -2);
2501 if (thislen < 0) {
2502 if (thislen == -1)
2503 return NULL;
2504 len = -1;
2505 break;
2506 }
2507 else if (len < 0 || thislen < len)
2508 len = thislen;
2509 }
Tim Peters67d687a2002-04-29 21:27:32 +00002510
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002511 /* allocate result list */
2512 if (len < 0)
2513 len = 10; /* arbitrary */
2514 if ((ret = PyList_New(len)) == NULL)
2515 return NULL;
Barry Warsawbd599b52000-08-03 15:45:29 +00002516
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002517 /* obtain iterators */
2518 itlist = PyTuple_New(itemsize);
2519 if (itlist == NULL)
2520 goto Fail_ret;
2521 for (i = 0; i < itemsize; ++i) {
2522 PyObject *item = PyTuple_GET_ITEM(args, i);
2523 PyObject *it = PyObject_GetIter(item);
2524 if (it == NULL) {
2525 if (PyErr_ExceptionMatches(PyExc_TypeError))
2526 PyErr_Format(PyExc_TypeError,
2527 "zip argument #%zd must support iteration",
2528 i+1);
2529 goto Fail_ret_itlist;
2530 }
2531 PyTuple_SET_ITEM(itlist, i, it);
2532 }
Barry Warsawbd599b52000-08-03 15:45:29 +00002533
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002534 /* build result into ret list */
2535 for (i = 0; ; ++i) {
2536 int j;
2537 PyObject *next = PyTuple_New(itemsize);
2538 if (!next)
2539 goto Fail_ret_itlist;
Tim Peters8572b4f2001-05-06 01:05:02 +00002540
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002541 for (j = 0; j < itemsize; j++) {
2542 PyObject *it = PyTuple_GET_ITEM(itlist, j);
2543 PyObject *item = PyIter_Next(it);
2544 if (!item) {
2545 if (PyErr_Occurred()) {
2546 Py_DECREF(ret);
2547 ret = NULL;
2548 }
2549 Py_DECREF(next);
2550 Py_DECREF(itlist);
2551 goto Done;
2552 }
2553 PyTuple_SET_ITEM(next, j, item);
2554 }
Tim Peters8572b4f2001-05-06 01:05:02 +00002555
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002556 if (i < len)
2557 PyList_SET_ITEM(ret, i, next);
2558 else {
2559 int status = PyList_Append(ret, next);
2560 Py_DECREF(next);
2561 ++len;
2562 if (status < 0)
2563 goto Fail_ret_itlist;
2564 }
2565 }
Tim Peters8572b4f2001-05-06 01:05:02 +00002566
Tim Peters67d687a2002-04-29 21:27:32 +00002567Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002568 if (ret != NULL && i < len) {
2569 /* The list is too big. */
2570 if (PyList_SetSlice(ret, i, len, NULL) < 0)
2571 return NULL;
2572 }
2573 return ret;
Tim Peters67d687a2002-04-29 21:27:32 +00002574
Tim Peters8572b4f2001-05-06 01:05:02 +00002575Fail_ret_itlist:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002576 Py_DECREF(itlist);
Tim Peters8572b4f2001-05-06 01:05:02 +00002577Fail_ret:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002578 Py_DECREF(ret);
2579 return NULL;
Barry Warsawbd599b52000-08-03 15:45:29 +00002580}
2581
2582
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002583PyDoc_STRVAR(zip_doc,
Barry Warsawbd599b52000-08-03 15:45:29 +00002584"zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2585\n\
2586Return a list of tuples, where each tuple contains the i-th element\n\
2587from each of the argument sequences. The returned list is truncated\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002588in length to the length of the shortest argument sequence.");
Barry Warsawbd599b52000-08-03 15:45:29 +00002589
2590
Guido van Rossum79f25d91997-04-29 20:08:16 +00002591static PyMethodDef builtin_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002592 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2593 {"abs", builtin_abs, METH_O, abs_doc},
2594 {"all", builtin_all, METH_O, all_doc},
2595 {"any", builtin_any, METH_O, any_doc},
2596 {"apply", builtin_apply, METH_VARARGS, apply_doc},
2597 {"bin", builtin_bin, METH_O, bin_doc},
2598 {"callable", builtin_callable, METH_O, callable_doc},
2599 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2600 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
2601 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
2602 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2603 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2604 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2605 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2606 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2607 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
2608 {"filter", builtin_filter, METH_VARARGS, filter_doc},
2609 {"format", builtin_format, METH_VARARGS, format_doc},
2610 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2611 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2612 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2613 {"hash", builtin_hash, METH_O, hash_doc},
2614 {"hex", builtin_hex, METH_O, hex_doc},
2615 {"id", builtin_id, METH_O, id_doc},
2616 {"input", builtin_input, METH_VARARGS, input_doc},
2617 {"intern", builtin_intern, METH_VARARGS, intern_doc},
2618 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2619 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2620 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2621 {"len", builtin_len, METH_O, len_doc},
2622 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2623 {"map", builtin_map, METH_VARARGS, map_doc},
2624 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2625 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2626 {"next", builtin_next, METH_VARARGS, next_doc},
2627 {"oct", builtin_oct, METH_O, oct_doc},
2628 {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
2629 {"ord", builtin_ord, METH_O, ord_doc},
2630 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2631 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2632 {"range", builtin_range, METH_VARARGS, range_doc},
2633 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
2634 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
2635 {"reload", builtin_reload, METH_O, reload_doc},
2636 {"repr", builtin_repr, METH_O, repr_doc},
2637 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2638 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2639 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2640 {"sum", builtin_sum, METH_VARARGS, sum_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002641#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002642 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002643#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002644 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2645 {"zip", builtin_zip, METH_VARARGS, zip_doc},
2646 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002647};
2648
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002649PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002650"Built-in functions, exceptions, and other objects.\n\
2651\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002652Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002653
Guido van Rossum25ce5661997-08-02 03:10:38 +00002654PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002655_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002656{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002657 PyObject *mod, *dict, *debug;
2658 mod = Py_InitModule4("__builtin__", builtin_methods,
2659 builtin_doc, (PyObject *)NULL,
2660 PYTHON_API_VERSION);
2661 if (mod == NULL)
2662 return NULL;
2663 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002664
Tim Peters7571a0f2003-03-23 17:52:28 +00002665#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002666 /* __builtin__ exposes a number of statically allocated objects
2667 * that, before this code was added in 2.3, never showed up in
2668 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2669 * result, programs leaking references to None and False (etc)
2670 * couldn't be diagnosed by examining sys.getobjects(0).
2671 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002672#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2673#else
2674#define ADD_TO_ALL(OBJECT) (void)0
2675#endif
2676
Tim Peters4b7625e2001-09-13 21:37:17 +00002677#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002678 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2679 return NULL; \
2680 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002681
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002682 SETBUILTIN("None", Py_None);
2683 SETBUILTIN("Ellipsis", Py_Ellipsis);
2684 SETBUILTIN("NotImplemented", Py_NotImplemented);
2685 SETBUILTIN("False", Py_False);
2686 SETBUILTIN("True", Py_True);
2687 SETBUILTIN("basestring", &PyBaseString_Type);
2688 SETBUILTIN("bool", &PyBool_Type);
2689 SETBUILTIN("memoryview", &PyMemoryView_Type);
2690 SETBUILTIN("bytearray", &PyByteArray_Type);
2691 SETBUILTIN("bytes", &PyString_Type);
2692 SETBUILTIN("buffer", &PyBuffer_Type);
2693 SETBUILTIN("classmethod", &PyClassMethod_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002694#ifndef WITHOUT_COMPLEX
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002695 SETBUILTIN("complex", &PyComplex_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002696#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002697 SETBUILTIN("dict", &PyDict_Type);
2698 SETBUILTIN("enumerate", &PyEnum_Type);
2699 SETBUILTIN("file", &PyFile_Type);
2700 SETBUILTIN("float", &PyFloat_Type);
2701 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2702 SETBUILTIN("property", &PyProperty_Type);
2703 SETBUILTIN("int", &PyInt_Type);
2704 SETBUILTIN("list", &PyList_Type);
2705 SETBUILTIN("long", &PyLong_Type);
2706 SETBUILTIN("object", &PyBaseObject_Type);
2707 SETBUILTIN("reversed", &PyReversed_Type);
2708 SETBUILTIN("set", &PySet_Type);
2709 SETBUILTIN("slice", &PySlice_Type);
2710 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2711 SETBUILTIN("str", &PyString_Type);
2712 SETBUILTIN("super", &PySuper_Type);
2713 SETBUILTIN("tuple", &PyTuple_Type);
2714 SETBUILTIN("type", &PyType_Type);
2715 SETBUILTIN("xrange", &PyRange_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002716#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002717 SETBUILTIN("unicode", &PyUnicode_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002718#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002719 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2720 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2721 Py_XDECREF(debug);
2722 return NULL;
2723 }
2724 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002725
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002726 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002727#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002728#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002729}
2730
Guido van Rossume77a7571993-11-03 15:01:26 +00002731/* Helper for filter(): filter a tuple through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002732
Guido van Rossum79f25d91997-04-29 20:08:16 +00002733static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002734filtertuple(PyObject *func, PyObject *tuple)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002735{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002736 PyObject *result;
2737 Py_ssize_t i, j;
2738 Py_ssize_t len = PyTuple_Size(tuple);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002739
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002740 if (len == 0) {
2741 if (PyTuple_CheckExact(tuple))
2742 Py_INCREF(tuple);
2743 else
2744 tuple = PyTuple_New(0);
2745 return tuple;
2746 }
Guido van Rossumb7b45621995-08-04 04:07:45 +00002747
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002748 if ((result = PyTuple_New(len)) == NULL)
2749 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002750
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002751 for (i = j = 0; i < len; ++i) {
2752 PyObject *item, *good;
2753 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002754
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002755 if (tuple->ob_type->tp_as_sequence &&
2756 tuple->ob_type->tp_as_sequence->sq_item) {
2757 item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
2758 if (item == NULL)
2759 goto Fail_1;
2760 } else {
2761 PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
2762 goto Fail_1;
2763 }
2764 if (func == Py_None) {
2765 Py_INCREF(item);
2766 good = item;
2767 }
2768 else {
2769 PyObject *arg = PyTuple_Pack(1, item);
2770 if (arg == NULL) {
2771 Py_DECREF(item);
2772 goto Fail_1;
2773 }
2774 good = PyEval_CallObject(func, arg);
2775 Py_DECREF(arg);
2776 if (good == NULL) {
2777 Py_DECREF(item);
2778 goto Fail_1;
2779 }
2780 }
2781 ok = PyObject_IsTrue(good);
2782 Py_DECREF(good);
2783 if (ok) {
2784 if (PyTuple_SetItem(result, j++, item) < 0)
2785 goto Fail_1;
2786 }
2787 else
2788 Py_DECREF(item);
2789 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002790
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002791 if (_PyTuple_Resize(&result, j) < 0)
2792 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002793
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002794 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002795
Guido van Rossum12d12c51993-10-26 17:58:25 +00002796Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002797 Py_DECREF(result);
2798 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002799}
2800
2801
Guido van Rossume77a7571993-11-03 15:01:26 +00002802/* Helper for filter(): filter a string through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002803
Guido van Rossum79f25d91997-04-29 20:08:16 +00002804static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002805filterstring(PyObject *func, PyObject *strobj)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002806{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002807 PyObject *result;
2808 Py_ssize_t i, j;
2809 Py_ssize_t len = PyString_Size(strobj);
2810 Py_ssize_t outlen = len;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002811
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002812 if (func == Py_None) {
2813 /* If it's a real string we can return the original,
2814 * as no character is ever false and __getitem__
2815 * does return this character. If it's a subclass
2816 * we must go through the __getitem__ loop */
2817 if (PyString_CheckExact(strobj)) {
2818 Py_INCREF(strobj);
2819 return strobj;
2820 }
2821 }
2822 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2823 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002824
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002825 for (i = j = 0; i < len; ++i) {
2826 PyObject *item;
2827 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002828
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002829 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2830 if (item == NULL)
2831 goto Fail_1;
2832 if (func==Py_None) {
2833 ok = 1;
2834 } else {
2835 PyObject *arg, *good;
2836 arg = PyTuple_Pack(1, item);
2837 if (arg == NULL) {
2838 Py_DECREF(item);
2839 goto Fail_1;
2840 }
2841 good = PyEval_CallObject(func, arg);
2842 Py_DECREF(arg);
2843 if (good == NULL) {
2844 Py_DECREF(item);
2845 goto Fail_1;
2846 }
2847 ok = PyObject_IsTrue(good);
2848 Py_DECREF(good);
2849 }
2850 if (ok) {
2851 Py_ssize_t reslen;
2852 if (!PyString_Check(item)) {
2853 PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
2854 " __getitem__ returned different type");
2855 Py_DECREF(item);
2856 goto Fail_1;
2857 }
2858 reslen = PyString_GET_SIZE(item);
2859 if (reslen == 1) {
2860 PyString_AS_STRING(result)[j++] =
2861 PyString_AS_STRING(item)[0];
2862 } else {
2863 /* do we need more space? */
2864 Py_ssize_t need = j;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002865
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002866 /* calculate space requirements while checking for overflow */
2867 if (need > PY_SSIZE_T_MAX - reslen) {
2868 Py_DECREF(item);
2869 goto Fail_1;
2870 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002871
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002872 need += reslen;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002873
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002874 if (need > PY_SSIZE_T_MAX - len) {
2875 Py_DECREF(item);
2876 goto Fail_1;
2877 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002878
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002879 need += len;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002880
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002881 if (need <= i) {
2882 Py_DECREF(item);
2883 goto Fail_1;
2884 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002885
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002886 need = need - i - 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002887
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002888 assert(need >= 0);
2889 assert(outlen >= 0);
Gregory P. Smith9d534572008-06-11 07:41:16 +00002890
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002891 if (need > outlen) {
2892 /* overallocate, to avoid reallocations */
2893 if (outlen > PY_SSIZE_T_MAX / 2) {
2894 Py_DECREF(item);
2895 return NULL;
2896 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002897
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002898 if (need<2*outlen) {
2899 need = 2*outlen;
2900 }
2901 if (_PyString_Resize(&result, need)) {
2902 Py_DECREF(item);
2903 return NULL;
2904 }
2905 outlen = need;
2906 }
2907 memcpy(
2908 PyString_AS_STRING(result) + j,
2909 PyString_AS_STRING(item),
2910 reslen
2911 );
2912 j += reslen;
2913 }
2914 }
2915 Py_DECREF(item);
2916 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002917
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002918 if (j < outlen)
2919 _PyString_Resize(&result, j);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002920
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002921 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002922
Guido van Rossum12d12c51993-10-26 17:58:25 +00002923Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002924 Py_DECREF(result);
2925 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002926}
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002927
2928#ifdef Py_USING_UNICODE
2929/* Helper for filter(): filter a Unicode object through a function */
2930
2931static PyObject *
2932filterunicode(PyObject *func, PyObject *strobj)
2933{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002934 PyObject *result;
2935 register Py_ssize_t i, j;
2936 Py_ssize_t len = PyUnicode_GetSize(strobj);
2937 Py_ssize_t outlen = len;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002938
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002939 if (func == Py_None) {
2940 /* If it's a real string we can return the original,
2941 * as no character is ever false and __getitem__
2942 * does return this character. If it's a subclass
2943 * we must go through the __getitem__ loop */
2944 if (PyUnicode_CheckExact(strobj)) {
2945 Py_INCREF(strobj);
2946 return strobj;
2947 }
2948 }
2949 if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
2950 return NULL;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002951
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002952 for (i = j = 0; i < len; ++i) {
2953 PyObject *item, *arg, *good;
2954 int ok;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002955
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002956 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2957 if (item == NULL)
2958 goto Fail_1;
2959 if (func == Py_None) {
2960 ok = 1;
2961 } else {
2962 arg = PyTuple_Pack(1, item);
2963 if (arg == NULL) {
2964 Py_DECREF(item);
2965 goto Fail_1;
2966 }
2967 good = PyEval_CallObject(func, arg);
2968 Py_DECREF(arg);
2969 if (good == NULL) {
2970 Py_DECREF(item);
2971 goto Fail_1;
2972 }
2973 ok = PyObject_IsTrue(good);
2974 Py_DECREF(good);
2975 }
2976 if (ok) {
2977 Py_ssize_t reslen;
2978 if (!PyUnicode_Check(item)) {
2979 PyErr_SetString(PyExc_TypeError,
2980 "can't filter unicode to unicode:"
2981 " __getitem__ returned different type");
2982 Py_DECREF(item);
2983 goto Fail_1;
2984 }
2985 reslen = PyUnicode_GET_SIZE(item);
2986 if (reslen == 1)
2987 PyUnicode_AS_UNICODE(result)[j++] =
2988 PyUnicode_AS_UNICODE(item)[0];
2989 else {
2990 /* do we need more space? */
2991 Py_ssize_t need = j + reslen + len - i - 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002992
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002993 /* check that didnt overflow */
2994 if ((j > PY_SSIZE_T_MAX - reslen) ||
2995 ((j + reslen) > PY_SSIZE_T_MAX - len) ||
2996 ((j + reslen + len) < i) ||
2997 ((j + reslen + len - i) <= 0)) {
2998 Py_DECREF(item);
2999 return NULL;
3000 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00003001
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003002 assert(need >= 0);
3003 assert(outlen >= 0);
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003004
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003005 if (need > outlen) {
3006 /* overallocate,
3007 to avoid reallocations */
3008 if (need < 2 * outlen) {
3009 if (outlen > PY_SSIZE_T_MAX / 2) {
3010 Py_DECREF(item);
3011 return NULL;
3012 } else {
3013 need = 2 * outlen;
3014 }
3015 }
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003016
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003017 if (PyUnicode_Resize(
3018 &result, need) < 0) {
3019 Py_DECREF(item);
3020 goto Fail_1;
3021 }
3022 outlen = need;
3023 }
3024 memcpy(PyUnicode_AS_UNICODE(result) + j,
3025 PyUnicode_AS_UNICODE(item),
3026 reslen*sizeof(Py_UNICODE));
3027 j += reslen;
3028 }
3029 }
3030 Py_DECREF(item);
3031 }
3032
3033 if (j < outlen)
3034 PyUnicode_Resize(&result, j);
3035
3036 return result;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003037
3038Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003039 Py_DECREF(result);
3040 return NULL;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003041}
3042#endif