blob: 3def0800aaabb5b4ead4de480bb3ecd3c9f0d458 [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\
R David Murray59488d22012-07-18 19:44:08 -040056Import a module. Because this function is meant for use by the Python\n\
57interpreter and not for general use it is better to use\n\
58importlib.import_module() to programmatically import a module.\n\
59\n\
60The globals argument is only used to determine the context;\n\
61they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000062should be a list of names to emulate ``from name import ...'', or an\n\
63empty list to emulate ``import name''.\n\
64When importing a module from a package, note that __import__('A.B', ...)\n\
65returns package A when fromlist is empty, but its submodule B when\n\
Neal Norwitz92e212f2006-04-03 04:48:37 +000066fromlist is not empty. Level is used to determine whether to perform \n\
67absolute or relative imports. -1 is the original strategy of attempting\n\
68both absolute and relative imports, 0 is absolute, a positive number\n\
69is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000070
Guido van Rossum1ae940a1995-01-02 19:04:15 +000071
Guido van Rossum79f25d91997-04-29 20:08:16 +000072static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000073builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +000074{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000075 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +000076}
77
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000078PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000079"abs(number) -> number\n\
80\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000081Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000082
Raymond Hettinger96229b12005-03-11 06:49:40 +000083static PyObject *
84builtin_all(PyObject *self, PyObject *v)
85{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000086 PyObject *it, *item;
87 PyObject *(*iternext)(PyObject *);
88 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +000089
Antoine Pitrouc83ea132010-05-09 14:46:46 +000090 it = PyObject_GetIter(v);
91 if (it == NULL)
92 return NULL;
93 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +000094
Antoine Pitrouc83ea132010-05-09 14:46:46 +000095 for (;;) {
96 item = iternext(it);
97 if (item == NULL)
98 break;
99 cmp = PyObject_IsTrue(item);
100 Py_DECREF(item);
101 if (cmp < 0) {
102 Py_DECREF(it);
103 return NULL;
104 }
105 if (cmp == 0) {
106 Py_DECREF(it);
107 Py_RETURN_FALSE;
108 }
109 }
110 Py_DECREF(it);
111 if (PyErr_Occurred()) {
112 if (PyErr_ExceptionMatches(PyExc_StopIteration))
113 PyErr_Clear();
114 else
115 return NULL;
116 }
117 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000118}
119
120PyDoc_STRVAR(all_doc,
121"all(iterable) -> bool\n\
122\n\
123Return True if bool(x) is True for all values x in the iterable.");
124
125static PyObject *
126builtin_any(PyObject *self, PyObject *v)
127{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000128 PyObject *it, *item;
129 PyObject *(*iternext)(PyObject *);
130 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000131
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000132 it = PyObject_GetIter(v);
133 if (it == NULL)
134 return NULL;
135 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000136
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000137 for (;;) {
138 item = iternext(it);
139 if (item == NULL)
140 break;
141 cmp = PyObject_IsTrue(item);
142 Py_DECREF(item);
143 if (cmp < 0) {
144 Py_DECREF(it);
145 return NULL;
146 }
147 if (cmp == 1) {
148 Py_DECREF(it);
149 Py_RETURN_TRUE;
150 }
151 }
152 Py_DECREF(it);
153 if (PyErr_Occurred()) {
154 if (PyErr_ExceptionMatches(PyExc_StopIteration))
155 PyErr_Clear();
156 else
157 return NULL;
158 }
159 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000160}
161
162PyDoc_STRVAR(any_doc,
163"any(iterable) -> bool\n\
164\n\
165Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000166
Guido van Rossum79f25d91997-04-29 20:08:16 +0000167static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000168builtin_apply(PyObject *self, PyObject *args)
Guido van Rossumc02e15c1991-12-16 13:03:00 +0000169{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000170 PyObject *func, *alist = NULL, *kwdict = NULL;
171 PyObject *t = NULL, *retval = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000172
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000173 if (PyErr_WarnPy3k("apply() not supported in 3.x; "
174 "use func(*args, **kwargs)", 1) < 0)
175 return NULL;
Neal Norwitz8b2bfbc2007-05-23 06:35:32 +0000176
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000177 if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))
178 return NULL;
179 if (alist != NULL) {
180 if (!PyTuple_Check(alist)) {
181 if (!PySequence_Check(alist)) {
182 PyErr_Format(PyExc_TypeError,
183 "apply() arg 2 expected sequence, found %s",
184 alist->ob_type->tp_name);
185 return NULL;
186 }
187 t = PySequence_Tuple(alist);
188 if (t == NULL)
189 return NULL;
190 alist = t;
191 }
192 }
193 if (kwdict != NULL && !PyDict_Check(kwdict)) {
194 PyErr_Format(PyExc_TypeError,
195 "apply() arg 3 expected dictionary, found %s",
196 kwdict->ob_type->tp_name);
197 goto finally;
198 }
199 retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
Barry Warsaw968f8cb1998-10-01 15:33:12 +0000200 finally:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000201 Py_XDECREF(t);
202 return retval;
Guido van Rossumc02e15c1991-12-16 13:03:00 +0000203}
204
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000205PyDoc_STRVAR(apply_doc,
Fred Drakef1fbc622001-01-12 17:05:05 +0000206"apply(object[, args[, kwargs]]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000207\n\
Fred Drake7b912121999-12-23 14:16:55 +0000208Call a callable object with positional arguments taken from the tuple args,\n\
209and keyword arguments taken from the optional dictionary kwargs.\n\
Raymond Hettingerff41c482003-04-06 09:01:11 +0000210Note that classes are callable, as are instances with a __call__() method.\n\
211\n\
212Deprecated since release 2.3. Instead, use the extended call syntax:\n\
213 function(*args, **keywords).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000214
215
Guido van Rossum79f25d91997-04-29 20:08:16 +0000216static PyObject *
Eric Smith3cd81942008-02-22 16:30:22 +0000217builtin_bin(PyObject *self, PyObject *v)
218{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000219 return PyNumber_ToBase(v, 2);
Eric Smith3cd81942008-02-22 16:30:22 +0000220}
221
222PyDoc_STRVAR(bin_doc,
223"bin(number) -> string\n\
224\n\
225Return the binary representation of an integer or long integer.");
226
227
228static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000229builtin_callable(PyObject *self, PyObject *v)
Guido van Rossum2d951851994-08-29 12:52:16 +0000230{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000231 return PyBool_FromLong((long)PyCallable_Check(v));
Guido van Rossum2d951851994-08-29 12:52:16 +0000232}
233
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000234PyDoc_STRVAR(callable_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000235"callable(object) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000236\n\
237Return whether the object is callable (i.e., some kind of function).\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000238Note that classes are callable, as are instances with a __call__() method.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000239
240
Guido van Rossum79f25d91997-04-29 20:08:16 +0000241static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000242builtin_filter(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000243{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000244 PyObject *func, *seq, *result, *it, *arg;
245 Py_ssize_t len; /* guess for result list size */
246 register Py_ssize_t j;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000247
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000248 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
249 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000250
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000251 /* Strings and tuples return a result of the same type. */
252 if (PyString_Check(seq))
253 return filterstring(func, seq);
Martin v. Löwis8afd7572003-01-25 22:46:11 +0000254#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000255 if (PyUnicode_Check(seq))
256 return filterunicode(func, seq);
Martin v. Löwis8afd7572003-01-25 22:46:11 +0000257#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000258 if (PyTuple_Check(seq))
259 return filtertuple(func, seq);
Tim Peters0e57abf2001-05-02 07:39:38 +0000260
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000261 /* Pre-allocate argument list tuple. */
262 arg = PyTuple_New(1);
263 if (arg == NULL)
264 return NULL;
Georg Brandle35b6572005-07-19 22:20:20 +0000265
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000266 /* Get iterator. */
267 it = PyObject_GetIter(seq);
268 if (it == NULL)
269 goto Fail_arg;
Tim Peters0e57abf2001-05-02 07:39:38 +0000270
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000271 /* Guess a result list size. */
272 len = _PyObject_LengthHint(seq, 8);
273 if (len == -1)
274 goto Fail_it;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000275
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000276 /* Get a result list. */
277 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
278 /* Eww - can modify the list in-place. */
279 Py_INCREF(seq);
280 result = seq;
281 }
282 else {
283 result = PyList_New(len);
284 if (result == NULL)
285 goto Fail_it;
286 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000287
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000288 /* Build the result list. */
289 j = 0;
290 for (;;) {
291 PyObject *item;
292 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000293
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000294 item = PyIter_Next(it);
295 if (item == NULL) {
296 if (PyErr_Occurred())
297 goto Fail_result_it;
298 break;
299 }
Guido van Rossumdc4b93d1993-10-27 14:56:44 +0000300
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000301 if (func == (PyObject *)&PyBool_Type || func == Py_None) {
302 ok = PyObject_IsTrue(item);
303 }
304 else {
305 PyObject *good;
306 PyTuple_SET_ITEM(arg, 0, item);
307 good = PyObject_Call(func, arg, NULL);
308 PyTuple_SET_ITEM(arg, 0, NULL);
309 if (good == NULL) {
310 Py_DECREF(item);
311 goto Fail_result_it;
312 }
313 ok = PyObject_IsTrue(good);
314 Py_DECREF(good);
315 }
316 if (ok) {
317 if (j < len)
318 PyList_SET_ITEM(result, j, item);
319 else {
320 int status = PyList_Append(result, item);
321 Py_DECREF(item);
322 if (status < 0)
323 goto Fail_result_it;
324 }
325 ++j;
326 }
327 else
328 Py_DECREF(item);
329 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000330
Guido van Rossum12d12c51993-10-26 17:58:25 +0000331
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000332 /* Cut back result list if len is too big. */
333 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
334 goto Fail_result_it;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000335
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000336 Py_DECREF(it);
337 Py_DECREF(arg);
338 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000339
Tim Peters0e57abf2001-05-02 07:39:38 +0000340Fail_result_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000341 Py_DECREF(result);
Tim Peters0e57abf2001-05-02 07:39:38 +0000342Fail_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000343 Py_DECREF(it);
Guido van Rossumc7903a12002-08-16 07:04:56 +0000344Fail_arg:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000345 Py_DECREF(arg);
346 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000347}
348
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000349PyDoc_STRVAR(filter_doc,
Tim Petersd50e5442002-03-09 00:06:26 +0000350"filter(function or None, sequence) -> list, tuple, or string\n"
351"\n"
352"Return those items of sequence for which function(item) is true. If\n"
353"function is None, return the items that are true. If sequence is a tuple\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000354"or string, return the same type, else return a list.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000355
Guido van Rossum79f25d91997-04-29 20:08:16 +0000356static PyObject *
Eric Smitha9f7d622008-02-17 19:46:49 +0000357builtin_format(PyObject *self, PyObject *args)
358{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000359 PyObject *value;
360 PyObject *format_spec = NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +0000361
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000362 if (!PyArg_ParseTuple(args, "O|O:format", &value, &format_spec))
363 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +0000364
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000365 return PyObject_Format(value, format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +0000366}
367
368PyDoc_STRVAR(format_doc,
369"format(value[, format_spec]) -> string\n\
370\n\
371Returns value.__format__(format_spec)\n\
372format_spec defaults to \"\"");
373
374static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000375builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000376{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000377 long x;
378 char s[1];
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000379
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000380 if (!PyArg_ParseTuple(args, "l:chr", &x))
381 return NULL;
382 if (x < 0 || x >= 256) {
383 PyErr_SetString(PyExc_ValueError,
384 "chr() arg not in range(256)");
385 return NULL;
386 }
387 s[0] = (char)x;
388 return PyString_FromStringAndSize(s, 1);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000389}
390
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000391PyDoc_STRVAR(chr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000392"chr(i) -> character\n\
393\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000394Return a string of one character with ordinal i; 0 <= i < 256.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000395
396
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000397#ifdef Py_USING_UNICODE
Guido van Rossum79f25d91997-04-29 20:08:16 +0000398static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000399builtin_unichr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000400{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000401 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000402
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000403 if (!PyArg_ParseTuple(args, "i:unichr", &x))
404 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000405
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000406 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000407}
408
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000409PyDoc_STRVAR(unichr_doc,
Fred Drake078b24f2000-04-13 02:42:50 +0000410"unichr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000411\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000412Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000413#endif
Guido van Rossum09095f32000-03-10 23:00:52 +0000414
415
416static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000417builtin_cmp(PyObject *self, PyObject *args)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000418{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000419 PyObject *a, *b;
420 int c;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000421
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000422 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
423 return NULL;
424 if (PyObject_Cmp(a, b, &c) < 0)
425 return NULL;
426 return PyInt_FromLong((long)c);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000427}
428
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000429PyDoc_STRVAR(cmp_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000430"cmp(x, y) -> integer\n\
431\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000432Return negative if x<y, zero if x==y, positive if x>y.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000433
434
Guido van Rossum79f25d91997-04-29 20:08:16 +0000435static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000436builtin_coerce(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000437{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000438 PyObject *v, *w;
439 PyObject *res;
Guido van Rossum5524a591995-01-10 15:26:20 +0000440
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000441 if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
442 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +0000443
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000444 if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
445 return NULL;
446 if (PyNumber_Coerce(&v, &w) < 0)
447 return NULL;
448 res = PyTuple_Pack(2, v, w);
449 Py_DECREF(v);
450 Py_DECREF(w);
451 return res;
Guido van Rossum04691fc1992-08-12 15:35:34 +0000452}
453
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000454PyDoc_STRVAR(coerce_doc,
Martin v. Löwis8d494f32004-08-25 10:42:41 +0000455"coerce(x, y) -> (x1, y1)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000456\n\
Martin v. Löwis8d494f32004-08-25 10:42:41 +0000457Return a tuple consisting of the two numeric arguments converted to\n\
458a common type, using the same rules as used by arithmetic operations.\n\
459If coercion is not possible, raise TypeError.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000460
Guido van Rossum79f25d91997-04-29 20:08:16 +0000461static PyObject *
Georg Brandl5240d742007-03-13 20:46:32 +0000462builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000463{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000464 char *str;
465 char *filename;
466 char *startstr;
467 int mode = -1;
468 int dont_inherit = 0;
469 int supplied_flags = 0;
470 int is_ast;
471 PyCompilerFlags cf;
472 PyObject *result = NULL, *cmd, *tmp = NULL;
473 Py_ssize_t length;
474 static char *kwlist[] = {"source", "filename", "mode", "flags",
475 "dont_inherit", NULL};
476 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000477
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000478 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
479 kwlist, &cmd, &filename, &startstr,
480 &supplied_flags, &dont_inherit))
481 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000482
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000483 cf.cf_flags = supplied_flags;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000484
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000485 if (supplied_flags &
486 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
487 {
488 PyErr_SetString(PyExc_ValueError,
489 "compile(): unrecognised flags");
490 return NULL;
491 }
492 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Georg Brandlfc8eef32008-03-28 12:11:56 +0000493
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000494 if (!dont_inherit) {
495 PyEval_MergeCompilerFlags(&cf);
496 }
Georg Brandlfc8eef32008-03-28 12:11:56 +0000497
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000498 if (strcmp(startstr, "exec") == 0)
499 mode = 0;
500 else if (strcmp(startstr, "eval") == 0)
501 mode = 1;
502 else if (strcmp(startstr, "single") == 0)
503 mode = 2;
504 else {
505 PyErr_SetString(PyExc_ValueError,
506 "compile() arg 3 must be 'exec', 'eval' or 'single'");
507 return NULL;
508 }
Georg Brandlf2bfd542008-03-29 13:24:23 +0000509
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000510 is_ast = PyAST_Check(cmd);
511 if (is_ast == -1)
512 return NULL;
513 if (is_ast) {
514 if (supplied_flags & PyCF_ONLY_AST) {
515 Py_INCREF(cmd);
516 result = cmd;
517 }
518 else {
519 PyArena *arena;
520 mod_ty mod;
Georg Brandlfc8eef32008-03-28 12:11:56 +0000521
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000522 arena = PyArena_New();
523 mod = PyAST_obj2mod(cmd, arena, mode);
524 if (mod == NULL) {
525 PyArena_Free(arena);
526 return NULL;
527 }
528 result = (PyObject*)PyAST_Compile(mod, filename,
529 &cf, arena);
530 PyArena_Free(arena);
531 }
532 return result;
533 }
Georg Brandlfc8eef32008-03-28 12:11:56 +0000534
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000535#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000536 if (PyUnicode_Check(cmd)) {
537 tmp = PyUnicode_AsUTF8String(cmd);
538 if (tmp == NULL)
539 return NULL;
540 cmd = tmp;
541 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
542 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000543#endif
Tim Peters6cd6a822001-08-17 22:11:27 +0000544
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000545 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))
546 goto cleanup;
547 if ((size_t)length != strlen(str)) {
548 PyErr_SetString(PyExc_TypeError,
549 "compile() expected string without null bytes");
550 goto cleanup;
551 }
552 result = Py_CompileStringFlags(str, filename, start[mode], &cf);
Neal Norwitz3a9a3e72005-11-27 20:38:31 +0000553cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000554 Py_XDECREF(tmp);
555 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000556}
557
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000558PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000559"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000560\n\
561Compile the source string (a Python module, statement or expression)\n\
562into a code object that can be executed by the exec statement or eval().\n\
563The filename will be used for run-time error messages.\n\
564The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000565single (interactive) statement, or 'eval' to compile an expression.\n\
566The flags argument, if present, controls which future statements influence\n\
567the compilation of the code.\n\
568The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
569the effects of any future statements in effect in the code calling\n\
570compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000571in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000572
Guido van Rossum79f25d91997-04-29 20:08:16 +0000573static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000574builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000575{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000576 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000577
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000578 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
579 return NULL;
580 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000581}
582
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000583PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000584"dir([object]) -> list of strings\n"
585"\n"
Georg Brandl871f1bc2007-03-12 13:17:36 +0000586"If called without an argument, return the names in the current scope.\n"
587"Else, return an alphabetized list of names comprising (some of) the attributes\n"
588"of the given object, and of attributes reachable from it.\n"
589"If the object supplies a method named __dir__, it will be used; otherwise\n"
590"the default dir() logic is used and returns:\n"
591" for a module object: the module's attributes.\n"
592" for a class object: its attributes, and recursively the attributes\n"
593" of its bases.\n"
Georg Brandl3bb15672007-03-13 07:23:16 +0000594" for any other object: its attributes, its class's attributes, and\n"
Georg Brandl871f1bc2007-03-12 13:17:36 +0000595" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000596
Guido van Rossum79f25d91997-04-29 20:08:16 +0000597static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000598builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000599{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000600 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000601
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000602 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
603 return NULL;
604 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000605}
606
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000607PyDoc_STRVAR(divmod_doc,
Raymond Hettinger39540a02011-07-19 11:59:20 -0700608"divmod(x, y) -> (quotient, remainder)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000609\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000610Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000611
612
Guido van Rossum79f25d91997-04-29 20:08:16 +0000613static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000614builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000615{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000616 PyObject *cmd, *result, *tmp = NULL;
617 PyObject *globals = Py_None, *locals = Py_None;
618 char *str;
619 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000620
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000621 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
622 return NULL;
623 if (locals != Py_None && !PyMapping_Check(locals)) {
624 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
625 return NULL;
626 }
627 if (globals != Py_None && !PyDict_Check(globals)) {
628 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
629 "globals must be a real dict; try eval(expr, {}, mapping)"
630 : "globals must be a dict");
631 return NULL;
632 }
633 if (globals == Py_None) {
634 globals = PyEval_GetGlobals();
635 if (locals == Py_None)
636 locals = PyEval_GetLocals();
637 }
638 else if (locals == Py_None)
639 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000640
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000641 if (globals == NULL || locals == NULL) {
642 PyErr_SetString(PyExc_TypeError,
643 "eval must be given globals and locals "
644 "when called without a frame");
645 return NULL;
646 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000647
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000648 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
649 if (PyDict_SetItemString(globals, "__builtins__",
650 PyEval_GetBuiltins()) != 0)
651 return NULL;
652 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000653
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000654 if (PyCode_Check(cmd)) {
655 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
656 PyErr_SetString(PyExc_TypeError,
657 "code object passed to eval() may not contain free variables");
658 return NULL;
659 }
660 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
661 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000662
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000663 if (!PyString_Check(cmd) &&
664 !PyUnicode_Check(cmd)) {
665 PyErr_SetString(PyExc_TypeError,
666 "eval() arg 1 must be a string or code object");
667 return NULL;
668 }
669 cf.cf_flags = 0;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000670
671#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000672 if (PyUnicode_Check(cmd)) {
673 tmp = PyUnicode_AsUTF8String(cmd);
674 if (tmp == NULL)
675 return NULL;
676 cmd = tmp;
677 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
678 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000679#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000680 if (PyString_AsStringAndSize(cmd, &str, NULL)) {
681 Py_XDECREF(tmp);
682 return NULL;
683 }
684 while (*str == ' ' || *str == '\t')
685 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000686
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000687 (void)PyEval_MergeCompilerFlags(&cf);
688 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
689 Py_XDECREF(tmp);
690 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000691}
692
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000693PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000694"eval(source[, globals[, locals]]) -> value\n\
695\n\
696Evaluate the source in the context of globals and locals.\n\
697The source may be a string representing a Python expression\n\
698or a code object as returned by compile().\n\
Neal Norwitz477ca1c2006-09-05 02:25:41 +0000699The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000700defaulting to the current globals and locals.\n\
701If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000702
703
Guido van Rossum79f25d91997-04-29 20:08:16 +0000704static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000705builtin_execfile(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000706{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000707 char *filename;
708 PyObject *globals = Py_None, *locals = Py_None;
709 PyObject *res;
710 FILE* fp = NULL;
711 PyCompilerFlags cf;
712 int exists;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000713
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000714 if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
715 1) < 0)
716 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +0000717
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000718 if (!PyArg_ParseTuple(args, "s|O!O:execfile",
719 &filename,
720 &PyDict_Type, &globals,
721 &locals))
722 return NULL;
723 if (locals != Py_None && !PyMapping_Check(locals)) {
724 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
725 return NULL;
726 }
727 if (globals == Py_None) {
728 globals = PyEval_GetGlobals();
729 if (locals == Py_None)
730 locals = PyEval_GetLocals();
731 }
732 else if (locals == Py_None)
733 locals = globals;
734 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
735 if (PyDict_SetItemString(globals, "__builtins__",
736 PyEval_GetBuiltins()) != 0)
737 return NULL;
738 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000739
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000740 exists = 0;
741 /* Test for existence or directory. */
Martin v. Löwis3484a182002-03-09 12:07:51 +0000742#if defined(PLAN9)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000743 {
744 Dir *d;
Martin v. Löwis3484a182002-03-09 12:07:51 +0000745
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000746 if ((d = dirstat(filename))!=nil) {
747 if(d->mode & DMDIR)
748 werrstr("is a directory");
749 else
750 exists = 1;
751 free(d);
752 }
753 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000754#elif defined(RISCOS)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000755 if (object_exists(filename)) {
756 if (isdir(filename))
757 errno = EISDIR;
758 else
759 exists = 1;
760 }
761#else /* standard Posix */
762 {
763 struct stat s;
764 if (stat(filename, &s) == 0) {
765 if (S_ISDIR(s.st_mode))
766# if defined(PYOS_OS2) && defined(PYCC_VACPP)
767 errno = EOS2ERR;
768# else
769 errno = EISDIR;
770# endif
771 else
772 exists = 1;
773 }
774 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000775#endif
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000776
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000777 if (exists) {
778 Py_BEGIN_ALLOW_THREADS
779 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
780 Py_END_ALLOW_THREADS
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000781
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000782 if (fp == NULL) {
783 exists = 0;
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000784 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000785 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000786
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000787 if (!exists) {
788 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
789 return NULL;
790 }
791 cf.cf_flags = 0;
792 if (PyEval_MergeCompilerFlags(&cf))
793 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
794 locals, 1, &cf);
795 else
796 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
797 locals, 1);
798 return res;
Guido van Rossum0f61f8a1992-02-25 18:55:05 +0000799}
800
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000801PyDoc_STRVAR(execfile_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000802"execfile(filename[, globals[, locals]])\n\
803\n\
804Read and execute a Python script from a file.\n\
805The globals and locals are dictionaries, defaulting to the current\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000806globals and locals. If only globals is given, locals defaults to it.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000807
808
Guido van Rossum79f25d91997-04-29 20:08:16 +0000809static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000810builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000811{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000812 PyObject *v, *result, *dflt = NULL;
813 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000814
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000815 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
816 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000817#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000818 if (PyUnicode_Check(name)) {
819 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
820 if (name == NULL)
821 return NULL;
822 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000823#endif
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000824
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000825 if (!PyString_Check(name)) {
826 PyErr_SetString(PyExc_TypeError,
827 "getattr(): attribute name must be string");
828 return NULL;
829 }
830 result = PyObject_GetAttr(v, name);
831 if (result == NULL && dflt != NULL &&
832 PyErr_ExceptionMatches(PyExc_AttributeError))
833 {
834 PyErr_Clear();
835 Py_INCREF(dflt);
836 result = dflt;
837 }
838 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000839}
840
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000841PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000842"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000843\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000844Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
845When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000846exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000847
848
Guido van Rossum79f25d91997-04-29 20:08:16 +0000849static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000850builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000851{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000852 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000853
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000854 d = PyEval_GetGlobals();
855 Py_XINCREF(d);
856 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000857}
858
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000859PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000860"globals() -> dictionary\n\
861\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000862Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000863
864
Guido van Rossum79f25d91997-04-29 20:08:16 +0000865static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000866builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000867{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000868 PyObject *v;
869 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000870
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000871 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
872 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000873#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000874 if (PyUnicode_Check(name)) {
875 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
876 if (name == NULL)
877 return NULL;
878 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000879#endif
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000880
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000881 if (!PyString_Check(name)) {
882 PyErr_SetString(PyExc_TypeError,
883 "hasattr(): attribute name must be string");
884 return NULL;
885 }
886 v = PyObject_GetAttr(v, name);
887 if (v == NULL) {
888 if (!PyErr_ExceptionMatches(PyExc_Exception))
889 return NULL;
890 else {
891 PyErr_Clear();
892 Py_INCREF(Py_False);
893 return Py_False;
894 }
895 }
896 Py_DECREF(v);
897 Py_INCREF(Py_True);
898 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000899}
900
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000901PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000902"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000903\n\
904Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000905(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000906
907
Guido van Rossum79f25d91997-04-29 20:08:16 +0000908static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000909builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000910{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000911 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000912}
913
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000914PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000915"id(object) -> integer\n\
916\n\
917Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000918simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000919
920
Guido van Rossum79f25d91997-04-29 20:08:16 +0000921static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000922builtin_map(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000923{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000924 typedef struct {
925 PyObject *it; /* the iterator object */
926 int saw_StopIteration; /* bool: did the iterator end? */
927 } sequence;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000928
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000929 PyObject *func, *result;
930 sequence *seqs = NULL, *sqp;
931 Py_ssize_t n, len;
932 register int i, j;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000933
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000934 n = PyTuple_Size(args);
935 if (n < 2) {
936 PyErr_SetString(PyExc_TypeError,
937 "map() requires at least two args");
938 return NULL;
939 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000940
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000941 func = PyTuple_GetItem(args, 0);
942 n--;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000943
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000944 if (func == Py_None) {
945 if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
946 "use list(...)", 1) < 0)
947 return NULL;
948 if (n == 1) {
949 /* map(None, S) is the same as list(S). */
950 return PySequence_List(PyTuple_GetItem(args, 1));
951 }
952 }
Guido van Rossumfa4ac711998-07-10 17:37:30 +0000953
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000954 /* Get space for sequence descriptors. Must NULL out the iterator
955 * pointers so that jumping to Fail_2 later doesn't see trash.
956 */
957 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
958 PyErr_NoMemory();
959 return NULL;
960 }
961 for (i = 0; i < n; ++i) {
962 seqs[i].it = (PyObject*)NULL;
963 seqs[i].saw_StopIteration = 0;
964 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000965
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000966 /* Do a first pass to obtain iterators for the arguments, and set len
967 * to the largest of their lengths.
968 */
969 len = 0;
970 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
971 PyObject *curseq;
972 Py_ssize_t curlen;
Guido van Rossumad991772001-01-12 16:03:05 +0000973
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000974 /* Get iterator. */
975 curseq = PyTuple_GetItem(args, i+1);
976 sqp->it = PyObject_GetIter(curseq);
977 if (sqp->it == NULL) {
978 static char errmsg[] =
979 "argument %d to map() must support iteration";
980 char errbuf[sizeof(errmsg) + 25];
981 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
982 PyErr_SetString(PyExc_TypeError, errbuf);
983 goto Fail_2;
984 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000985
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000986 /* Update len. */
987 curlen = _PyObject_LengthHint(curseq, 8);
988 if (curlen > len)
989 len = curlen;
990 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000991
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000992 /* Get space for the result list. */
993 if ((result = (PyObject *) PyList_New(len)) == NULL)
994 goto Fail_2;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000995
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000996 /* Iterate over the sequences until all have stopped. */
997 for (i = 0; ; ++i) {
998 PyObject *alist, *item=NULL, *value;
999 int numactive = 0;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001000
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001001 if (func == Py_None && n == 1)
1002 alist = NULL;
1003 else if ((alist = PyTuple_New(n)) == NULL)
1004 goto Fail_1;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001005
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001006 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
1007 if (sqp->saw_StopIteration) {
1008 Py_INCREF(Py_None);
1009 item = Py_None;
1010 }
1011 else {
1012 item = PyIter_Next(sqp->it);
1013 if (item)
1014 ++numactive;
1015 else {
1016 if (PyErr_Occurred()) {
1017 Py_XDECREF(alist);
1018 goto Fail_1;
1019 }
1020 Py_INCREF(Py_None);
1021 item = Py_None;
1022 sqp->saw_StopIteration = 1;
1023 }
1024 }
1025 if (alist)
1026 PyTuple_SET_ITEM(alist, j, item);
1027 else
1028 break;
1029 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001030
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001031 if (!alist)
1032 alist = item;
Guido van Rossum2d951851994-08-29 12:52:16 +00001033
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001034 if (numactive == 0) {
1035 Py_DECREF(alist);
1036 break;
1037 }
Guido van Rossum2d951851994-08-29 12:52:16 +00001038
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001039 if (func == Py_None)
1040 value = alist;
1041 else {
1042 value = PyEval_CallObject(func, alist);
1043 Py_DECREF(alist);
1044 if (value == NULL)
1045 goto Fail_1;
1046 }
1047 if (i >= len) {
1048 int status = PyList_Append(result, value);
1049 Py_DECREF(value);
1050 if (status < 0)
1051 goto Fail_1;
1052 }
1053 else if (PyList_SetItem(result, i, value) < 0)
1054 goto Fail_1;
1055 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001056
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001057 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
1058 goto Fail_1;
Guido van Rossumfa4ac711998-07-10 17:37:30 +00001059
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001060 goto Succeed;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001061
Guido van Rossum12d12c51993-10-26 17:58:25 +00001062Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001063 Py_DECREF(result);
Guido van Rossum12d12c51993-10-26 17:58:25 +00001064Fail_2:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001065 result = NULL;
Tim Peters4e9afdc2001-05-03 23:54:49 +00001066Succeed:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001067 assert(seqs);
1068 for (i = 0; i < n; ++i)
1069 Py_XDECREF(seqs[i].it);
1070 PyMem_DEL(seqs);
1071 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001072}
1073
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001074PyDoc_STRVAR(map_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001075"map(function, sequence[, sequence, ...]) -> list\n\
1076\n\
1077Return a list of the results of applying the function to the items of\n\
1078the argument sequence(s). If more than one sequence is given, the\n\
1079function is called with an argument list consisting of the corresponding\n\
1080item of each sequence, substituting None for missing values when not all\n\
1081sequences have the same length. If the function is None, return a list of\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001082the items of the sequence (or a list of tuples if more than one sequence).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001083
1084
Guido van Rossum79f25d91997-04-29 20:08:16 +00001085static PyObject *
Georg Brandl28e08732008-04-30 19:47:09 +00001086builtin_next(PyObject *self, PyObject *args)
1087{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001088 PyObject *it, *res;
1089 PyObject *def = NULL;
Georg Brandl28e08732008-04-30 19:47:09 +00001090
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001091 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1092 return NULL;
1093 if (!PyIter_Check(it)) {
1094 PyErr_Format(PyExc_TypeError,
1095 "%.200s object is not an iterator",
1096 it->ob_type->tp_name);
1097 return NULL;
1098 }
1099
1100 res = (*it->ob_type->tp_iternext)(it);
1101 if (res != NULL) {
1102 return res;
1103 } else if (def != NULL) {
1104 if (PyErr_Occurred()) {
1105 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
1106 return NULL;
1107 PyErr_Clear();
1108 }
1109 Py_INCREF(def);
1110 return def;
1111 } else if (PyErr_Occurred()) {
1112 return NULL;
1113 } else {
1114 PyErr_SetNone(PyExc_StopIteration);
1115 return NULL;
1116 }
Georg Brandl28e08732008-04-30 19:47:09 +00001117}
1118
1119PyDoc_STRVAR(next_doc,
1120"next(iterator[, default])\n\
1121\n\
1122Return the next item from the iterator. If default is given and the iterator\n\
1123is exhausted, it is returned instead of raising StopIteration.");
1124
1125
1126static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001127builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001128{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001129 PyObject *v;
1130 PyObject *name;
1131 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001132
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001133 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1134 return NULL;
1135 if (PyObject_SetAttr(v, name, value) != 0)
1136 return NULL;
1137 Py_INCREF(Py_None);
1138 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001139}
1140
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001141PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001142"setattr(object, name, value)\n\
1143\n\
1144Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001145``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001146
1147
Guido van Rossum79f25d91997-04-29 20:08:16 +00001148static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001149builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001150{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001151 PyObject *v;
1152 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001153
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001154 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1155 return NULL;
1156 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1157 return NULL;
1158 Py_INCREF(Py_None);
1159 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001160}
1161
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001162PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001163"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001164\n\
1165Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001166``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001167
1168
Guido van Rossum79f25d91997-04-29 20:08:16 +00001169static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001170builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001171{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001172 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001173
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001174 x = PyObject_Hash(v);
1175 if (x == -1)
1176 return NULL;
1177 return PyInt_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001178}
1179
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001180PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001181"hash(object) -> integer\n\
1182\n\
1183Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001184the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001185
1186
Guido van Rossum79f25d91997-04-29 20:08:16 +00001187static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001188builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001189{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001190 PyNumberMethods *nb;
1191 PyObject *res;
Benjamin Petersonc6d64ec2008-05-17 20:09:42 +00001192
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001193 if ((nb = v->ob_type->tp_as_number) == NULL ||
1194 nb->nb_hex == NULL) {
1195 PyErr_SetString(PyExc_TypeError,
1196 "hex() argument can't be converted to hex");
1197 return NULL;
1198 }
1199 res = (*nb->nb_hex)(v);
1200 if (res && !PyString_Check(res)) {
1201 PyErr_Format(PyExc_TypeError,
1202 "__hex__ returned non-string (type %.200s)",
1203 res->ob_type->tp_name);
1204 Py_DECREF(res);
1205 return NULL;
1206 }
1207 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001208}
1209
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001210PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001211"hex(number) -> string\n\
1212\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001213Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001214
1215
Tim Petersdbd9ba62000-07-09 03:09:57 +00001216static PyObject *builtin_raw_input(PyObject *, PyObject *);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001217
Guido van Rossum79f25d91997-04-29 20:08:16 +00001218static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001219builtin_input(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001220{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001221 PyObject *line;
1222 char *str;
1223 PyObject *res;
1224 PyObject *globals, *locals;
1225 PyCompilerFlags cf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001226
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001227 line = builtin_raw_input(self, args);
1228 if (line == NULL)
1229 return line;
1230 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1231 return NULL;
1232 while (*str == ' ' || *str == '\t')
1233 str++;
1234 globals = PyEval_GetGlobals();
1235 locals = PyEval_GetLocals();
1236 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1237 if (PyDict_SetItemString(globals, "__builtins__",
1238 PyEval_GetBuiltins()) != 0)
1239 return NULL;
1240 }
1241 cf.cf_flags = 0;
1242 PyEval_MergeCompilerFlags(&cf);
1243 res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1244 Py_DECREF(line);
1245 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001246}
1247
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001248PyDoc_STRVAR(input_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001249"input([prompt]) -> value\n\
1250\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001251Equivalent to eval(raw_input(prompt)).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001252
1253
Guido van Rossume8811f81997-02-14 15:48:05 +00001254static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001255builtin_intern(PyObject *self, PyObject *args)
Guido van Rossume8811f81997-02-14 15:48:05 +00001256{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001257 PyObject *s;
1258 if (!PyArg_ParseTuple(args, "S:intern", &s))
1259 return NULL;
1260 if (!PyString_CheckExact(s)) {
1261 PyErr_SetString(PyExc_TypeError,
1262 "can't intern subclass of string");
1263 return NULL;
1264 }
1265 Py_INCREF(s);
1266 PyString_InternInPlace(&s);
1267 return s;
Guido van Rossume8811f81997-02-14 15:48:05 +00001268}
1269
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001270PyDoc_STRVAR(intern_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001271"intern(string) -> string\n\
1272\n\
1273``Intern'' the given string. This enters the string in the (global)\n\
1274table of interned strings whose purpose is to speed up dictionary lookups.\n\
1275Return the string itself or the previously interned string object with the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001276same value.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001277
1278
Guido van Rossum79f25d91997-04-29 20:08:16 +00001279static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001280builtin_iter(PyObject *self, PyObject *args)
1281{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001282 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001283
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001284 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1285 return NULL;
1286 if (w == NULL)
1287 return PyObject_GetIter(v);
1288 if (!PyCallable_Check(v)) {
1289 PyErr_SetString(PyExc_TypeError,
1290 "iter(v, w): v must be callable");
1291 return NULL;
1292 }
1293 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001294}
1295
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001296PyDoc_STRVAR(iter_doc,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001297"iter(collection) -> iterator\n\
1298iter(callable, sentinel) -> iterator\n\
1299\n\
1300Get an iterator from an object. In the first form, the argument must\n\
1301supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001302In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001303
1304
1305static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001306builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001307{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001308 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001309
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001310 res = PyObject_Size(v);
1311 if (res < 0 && PyErr_Occurred())
1312 return NULL;
1313 return PyInt_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001314}
1315
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001316PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001317"len(object) -> integer\n\
1318\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001319Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001320
1321
Guido van Rossum79f25d91997-04-29 20:08:16 +00001322static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001323builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001324{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001325 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001326
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001327 d = PyEval_GetLocals();
1328 Py_XINCREF(d);
1329 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001330}
1331
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001332PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001333"locals() -> dictionary\n\
1334\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001335Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001336
1337
Guido van Rossum79f25d91997-04-29 20:08:16 +00001338static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001339min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001340{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001341 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1342 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001343
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001344 if (PyTuple_Size(args) > 1)
1345 v = args;
1346 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1347 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001348
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001349 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1350 keyfunc = PyDict_GetItemString(kwds, "key");
1351 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1352 PyErr_Format(PyExc_TypeError,
1353 "%s() got an unexpected keyword argument", name);
1354 return NULL;
1355 }
1356 Py_INCREF(keyfunc);
1357 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001358
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001359 it = PyObject_GetIter(v);
1360 if (it == NULL) {
1361 Py_XDECREF(keyfunc);
1362 return NULL;
1363 }
Tim Petersc3074532001-05-03 07:00:32 +00001364
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001365 maxitem = NULL; /* the result */
1366 maxval = NULL; /* the value associated with the result */
1367 while (( item = PyIter_Next(it) )) {
1368 /* get the value from the key function */
1369 if (keyfunc != NULL) {
1370 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1371 if (val == NULL)
1372 goto Fail_it_item;
1373 }
1374 /* no key function; the value is the item */
1375 else {
1376 val = item;
1377 Py_INCREF(val);
1378 }
Tim Petersc3074532001-05-03 07:00:32 +00001379
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001380 /* maximum value and item are unset; set them */
1381 if (maxval == NULL) {
1382 maxitem = item;
1383 maxval = val;
1384 }
1385 /* maximum value and item are set; update them as necessary */
1386 else {
1387 int cmp = PyObject_RichCompareBool(val, maxval, op);
1388 if (cmp < 0)
1389 goto Fail_it_item_and_val;
1390 else if (cmp > 0) {
1391 Py_DECREF(maxval);
1392 Py_DECREF(maxitem);
1393 maxval = val;
1394 maxitem = item;
1395 }
1396 else {
1397 Py_DECREF(item);
1398 Py_DECREF(val);
1399 }
1400 }
1401 }
1402 if (PyErr_Occurred())
1403 goto Fail_it;
1404 if (maxval == NULL) {
1405 PyErr_Format(PyExc_ValueError,
1406 "%s() arg is an empty sequence", name);
1407 assert(maxitem == NULL);
1408 }
1409 else
1410 Py_DECREF(maxval);
1411 Py_DECREF(it);
1412 Py_XDECREF(keyfunc);
1413 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001414
1415Fail_it_item_and_val:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001416 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001417Fail_it_item:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001418 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001419Fail_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001420 Py_XDECREF(maxval);
1421 Py_XDECREF(maxitem);
1422 Py_DECREF(it);
1423 Py_XDECREF(keyfunc);
1424 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001425}
1426
Guido van Rossum79f25d91997-04-29 20:08:16 +00001427static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001428builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001429{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001430 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001431}
1432
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001433PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001434"min(iterable[, key=func]) -> value\n\
1435min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001436\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001437With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001438With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001439
1440
Guido van Rossum79f25d91997-04-29 20:08:16 +00001441static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001442builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001443{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001444 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001445}
1446
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001447PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001448"max(iterable[, key=func]) -> value\n\
1449max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001450\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001451With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001452With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001453
1454
Guido van Rossum79f25d91997-04-29 20:08:16 +00001455static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001456builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001457{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001458 PyNumberMethods *nb;
1459 PyObject *res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001460
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001461 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1462 nb->nb_oct == NULL) {
1463 PyErr_SetString(PyExc_TypeError,
1464 "oct() argument can't be converted to oct");
1465 return NULL;
1466 }
1467 res = (*nb->nb_oct)(v);
1468 if (res && !PyString_Check(res)) {
1469 PyErr_Format(PyExc_TypeError,
1470 "__oct__ returned non-string (type %.200s)",
1471 res->ob_type->tp_name);
1472 Py_DECREF(res);
1473 return NULL;
1474 }
1475 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001476}
1477
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001478PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001479"oct(number) -> string\n\
1480\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001481Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001482
1483
Guido van Rossum79f25d91997-04-29 20:08:16 +00001484static PyObject *
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001485builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
1486{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001487 return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001488}
1489
1490PyDoc_STRVAR(open_doc,
1491"open(name[, mode[, buffering]]) -> file object\n\
1492\n\
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00001493Open a file using the file() type, returns a file object. This is the\n\
Philip Jenveydd0388a2009-05-28 03:12:16 +00001494preferred way to open a file. See file.__doc__ for further information.");
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001495
1496
1497static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001498builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001499{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001500 long ord;
1501 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001502
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001503 if (PyString_Check(obj)) {
1504 size = PyString_GET_SIZE(obj);
1505 if (size == 1) {
1506 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1507 return PyInt_FromLong(ord);
1508 }
1509 } else if (PyByteArray_Check(obj)) {
1510 size = PyByteArray_GET_SIZE(obj);
1511 if (size == 1) {
1512 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1513 return PyInt_FromLong(ord);
1514 }
Christian Heimes1a6387e2008-03-26 12:49:49 +00001515
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001516#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001517 } else if (PyUnicode_Check(obj)) {
1518 size = PyUnicode_GET_SIZE(obj);
1519 if (size == 1) {
1520 ord = (long)*PyUnicode_AS_UNICODE(obj);
1521 return PyInt_FromLong(ord);
1522 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001523#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001524 } else {
1525 PyErr_Format(PyExc_TypeError,
1526 "ord() expected string of length 1, but " \
1527 "%.200s found", obj->ob_type->tp_name);
1528 return NULL;
1529 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001530
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001531 PyErr_Format(PyExc_TypeError,
1532 "ord() expected a character, "
1533 "but string of length %zd found",
1534 size);
1535 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001536}
1537
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001538PyDoc_STRVAR(ord_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001539"ord(c) -> integer\n\
1540\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001541Return the integer ordinal of a one-character string.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001542
1543
Guido van Rossum79f25d91997-04-29 20:08:16 +00001544static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001545builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001546{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001547 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001548
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001549 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1550 return NULL;
1551 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001552}
1553
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001554PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001555"pow(x, y[, z]) -> number\n\
1556\n\
1557With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001558equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001559
1560
Eric Smith7c478942008-03-18 23:45:49 +00001561static PyObject *
1562builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1563{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001564 static char *kwlist[] = {"sep", "end", "file", 0};
1565 static PyObject *dummy_args = NULL;
1566 static PyObject *unicode_newline = NULL, *unicode_space = NULL;
1567 static PyObject *str_newline = NULL, *str_space = NULL;
1568 PyObject *newline, *space;
1569 PyObject *sep = NULL, *end = NULL, *file = NULL;
1570 int i, err, use_unicode = 0;
Eric Smith7c478942008-03-18 23:45:49 +00001571
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001572 if (dummy_args == NULL) {
1573 if (!(dummy_args = PyTuple_New(0)))
1574 return NULL;
1575 }
1576 if (str_newline == NULL) {
1577 str_newline = PyString_FromString("\n");
1578 if (str_newline == NULL)
1579 return NULL;
1580 str_space = PyString_FromString(" ");
1581 if (str_space == NULL) {
1582 Py_CLEAR(str_newline);
1583 return NULL;
1584 }
Martin v. Löwised11a5d2012-05-20 10:42:17 +02001585#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001586 unicode_newline = PyUnicode_FromString("\n");
1587 if (unicode_newline == NULL) {
1588 Py_CLEAR(str_newline);
1589 Py_CLEAR(str_space);
1590 return NULL;
1591 }
1592 unicode_space = PyUnicode_FromString(" ");
1593 if (unicode_space == NULL) {
1594 Py_CLEAR(str_newline);
1595 Py_CLEAR(str_space);
1596 Py_CLEAR(unicode_space);
1597 return NULL;
1598 }
Martin v. Löwised11a5d2012-05-20 10:42:17 +02001599#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001600 }
1601 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1602 kwlist, &sep, &end, &file))
1603 return NULL;
1604 if (file == NULL || file == Py_None) {
1605 file = PySys_GetObject("stdout");
1606 /* sys.stdout may be None when FILE* stdout isn't connected */
1607 if (file == Py_None)
1608 Py_RETURN_NONE;
1609 }
1610 if (sep == Py_None) {
1611 sep = NULL;
1612 }
1613 else if (sep) {
1614 if (PyUnicode_Check(sep)) {
1615 use_unicode = 1;
1616 }
1617 else if (!PyString_Check(sep)) {
1618 PyErr_Format(PyExc_TypeError,
1619 "sep must be None, str or unicode, not %.200s",
1620 sep->ob_type->tp_name);
1621 return NULL;
1622 }
1623 }
1624 if (end == Py_None)
1625 end = NULL;
1626 else if (end) {
1627 if (PyUnicode_Check(end)) {
1628 use_unicode = 1;
1629 }
1630 else if (!PyString_Check(end)) {
1631 PyErr_Format(PyExc_TypeError,
1632 "end must be None, str or unicode, not %.200s",
1633 end->ob_type->tp_name);
1634 return NULL;
1635 }
1636 }
Benjamin Peterson753d1622009-07-02 18:16:45 +00001637
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001638 if (!use_unicode) {
1639 for (i = 0; i < PyTuple_Size(args); i++) {
1640 if (PyUnicode_Check(PyTuple_GET_ITEM(args, i))) {
1641 use_unicode = 1;
1642 break;
1643 }
1644 }
1645 }
1646 if (use_unicode) {
1647 newline = unicode_newline;
1648 space = unicode_space;
1649 }
1650 else {
1651 newline = str_newline;
1652 space = str_space;
1653 }
Eric Smith7c478942008-03-18 23:45:49 +00001654
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001655 for (i = 0; i < PyTuple_Size(args); i++) {
1656 if (i > 0) {
1657 if (sep == NULL)
1658 err = PyFile_WriteObject(space, file,
1659 Py_PRINT_RAW);
1660 else
1661 err = PyFile_WriteObject(sep, file,
1662 Py_PRINT_RAW);
1663 if (err)
1664 return NULL;
1665 }
1666 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1667 Py_PRINT_RAW);
1668 if (err)
1669 return NULL;
1670 }
Eric Smith7c478942008-03-18 23:45:49 +00001671
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001672 if (end == NULL)
1673 err = PyFile_WriteObject(newline, file, Py_PRINT_RAW);
1674 else
1675 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1676 if (err)
1677 return NULL;
Eric Smith7c478942008-03-18 23:45:49 +00001678
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001679 Py_RETURN_NONE;
Eric Smith7c478942008-03-18 23:45:49 +00001680}
1681
1682PyDoc_STRVAR(print_doc,
1683"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
1684\n\
1685Prints the values to a stream, or to sys.stdout by default.\n\
1686Optional keyword arguments:\n\
1687file: a file-like object (stream); defaults to the current sys.stdout.\n\
1688sep: string inserted between values, default a space.\n\
1689end: string appended after the last value, default a newline.");
1690
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001691
1692/* Return number of items in range (lo, hi, step), when arguments are
1693 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1694 * & only if the true value is too large to fit in a signed long.
1695 * Arguments MUST return 1 with either PyInt_Check() or
1696 * PyLong_Check(). Return -1 when there is an error.
1697 */
1698static long
1699get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
1700{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001701 /* -------------------------------------------------------------
1702 Algorithm is equal to that of get_len_of_range(), but it operates
1703 on PyObjects (which are assumed to be PyLong or PyInt objects).
1704 ---------------------------------------------------------------*/
1705 long n;
1706 PyObject *diff = NULL;
1707 PyObject *one = NULL;
1708 PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
1709 /* holds sub-expression evaluations */
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001710
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001711 /* if (lo >= hi), return length of 0. */
1712 if (PyObject_Compare(lo, hi) >= 0)
1713 return 0;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001714
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001715 if ((one = PyLong_FromLong(1L)) == NULL)
1716 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001717
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001718 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
1719 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001720
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001721 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
1722 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001723
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001724 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
1725 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001726
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001727 if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
1728 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001729
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001730 n = PyLong_AsLong(tmp3);
1731 if (PyErr_Occurred()) { /* Check for Overflow */
1732 PyErr_Clear();
1733 goto Fail;
1734 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001735
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001736 Py_DECREF(tmp3);
1737 Py_DECREF(tmp2);
1738 Py_DECREF(diff);
1739 Py_DECREF(tmp1);
1740 Py_DECREF(one);
1741 return n;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001742
1743 Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001744 Py_XDECREF(tmp3);
1745 Py_XDECREF(tmp2);
1746 Py_XDECREF(diff);
1747 Py_XDECREF(tmp1);
1748 Py_XDECREF(one);
1749 return -1;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001750}
1751
Mark Dickinsona8d26682010-05-04 16:18:25 +00001752/* Helper function for handle_range_longs. If arg is int or long
1753 object, returns it with incremented reference count. If arg is
1754 float, raises type error. As a last resort, creates a new int by
1755 calling arg type's nb_int method if it is defined. Returns NULL
1756 and sets exception on error.
1757
1758 Returns a new reference to an int object. */
1759static PyObject *
1760get_range_long_argument(PyObject *arg, const char *name)
1761{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001762 PyObject *v;
1763 PyNumberMethods *nb;
1764 if (PyInt_Check(arg) || PyLong_Check(arg)) {
1765 Py_INCREF(arg);
1766 return arg;
1767 }
1768 if (PyFloat_Check(arg) ||
1769 (nb = Py_TYPE(arg)->tp_as_number) == NULL ||
1770 nb->nb_int == NULL) {
1771 PyErr_Format(PyExc_TypeError,
1772 "range() integer %s argument expected, got %s.",
1773 name, arg->ob_type->tp_name);
1774 return NULL;
1775 }
1776 v = nb->nb_int(arg);
1777 if (v == NULL)
1778 return NULL;
1779 if (PyInt_Check(v) || PyLong_Check(v))
1780 return v;
1781 Py_DECREF(v);
1782 PyErr_SetString(PyExc_TypeError,
1783 "__int__ should return int object");
1784 return NULL;
Mark Dickinsona8d26682010-05-04 16:18:25 +00001785}
1786
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001787/* An extension of builtin_range() that handles the case when PyLong
1788 * arguments are given. */
1789static PyObject *
Mark Dickinsonef9b4ab2010-05-04 16:19:06 +00001790handle_range_longs(PyObject *self, PyObject *args)
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001791{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001792 PyObject *ilow = NULL;
1793 PyObject *ihigh = NULL;
1794 PyObject *istep = NULL;
Tim Peters874e1f72003-04-13 22:13:08 +00001795
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001796 PyObject *low = NULL;
1797 PyObject *high = NULL;
1798 PyObject *step = NULL;
Mark Dickinsona8d26682010-05-04 16:18:25 +00001799
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001800 PyObject *curnum = NULL;
1801 PyObject *v = NULL;
1802 long bign;
1803 Py_ssize_t i, n;
1804 int cmp_result;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001805
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001806 PyObject *zero = PyLong_FromLong(0);
Tim Peters874e1f72003-04-13 22:13:08 +00001807
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001808 if (zero == NULL)
1809 return NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001810
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001811 if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
1812 Py_DECREF(zero);
1813 return NULL;
1814 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001815
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001816 /* Figure out which way we were called, supply defaults, and be
1817 * sure to incref everything so that the decrefs at the end
1818 * are correct. NB: ilow, ihigh and istep are borrowed references.
1819 */
1820 assert(ilow != NULL);
1821 if (ihigh == NULL) {
1822 /* only 1 arg -- it's the upper limit */
1823 ihigh = ilow;
1824 ilow = NULL;
1825 }
Mark Dickinsona8d26682010-05-04 16:18:25 +00001826
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001827 /* convert ihigh if necessary */
1828 assert(ihigh != NULL);
1829 high = get_range_long_argument(ihigh, "end");
1830 if (high == NULL)
1831 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001832
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001833 /* ihigh correct now; do ilow */
1834 if (ilow == NULL) {
1835 Py_INCREF(zero);
1836 low = zero;
1837 }
1838 else {
1839 low = get_range_long_argument(ilow, "start");
1840 if (low == NULL)
1841 goto Fail;
1842 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001843
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001844 /* ilow and ihigh correct now; do istep */
1845 if (istep == NULL)
1846 step = PyLong_FromLong(1);
1847 else
1848 step = get_range_long_argument(istep, "step");
1849 if (step == NULL)
1850 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001851
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001852 if (PyObject_Cmp(step, zero, &cmp_result) == -1)
1853 goto Fail;
Tim Peters874e1f72003-04-13 22:13:08 +00001854
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001855 if (cmp_result == 0) {
1856 PyErr_SetString(PyExc_ValueError,
1857 "range() step argument must not be zero");
1858 goto Fail;
1859 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001860
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001861 if (cmp_result > 0)
1862 bign = get_len_of_range_longs(low, high, step);
1863 else {
1864 PyObject *neg_step = PyNumber_Negative(step);
1865 if (neg_step == NULL)
1866 goto Fail;
1867 bign = get_len_of_range_longs(high, low, neg_step);
1868 Py_DECREF(neg_step);
1869 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001870
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001871 n = (Py_ssize_t)bign;
1872 if (bign < 0 || (long)n != bign) {
1873 PyErr_SetString(PyExc_OverflowError,
1874 "range() result has too many items");
1875 goto Fail;
1876 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001877
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001878 v = PyList_New(n);
1879 if (v == NULL)
1880 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001881
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001882 curnum = low;
1883 Py_INCREF(curnum);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001884
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001885 for (i = 0; i < n; i++) {
1886 PyObject *w = PyNumber_Long(curnum);
1887 PyObject *tmp_num;
1888 if (w == NULL)
1889 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001890
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001891 PyList_SET_ITEM(v, i, w);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001892
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001893 tmp_num = PyNumber_Add(curnum, step);
1894 if (tmp_num == NULL)
1895 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001896
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001897 Py_DECREF(curnum);
1898 curnum = tmp_num;
1899 }
1900 Py_DECREF(low);
1901 Py_DECREF(high);
1902 Py_DECREF(step);
1903 Py_DECREF(zero);
1904 Py_DECREF(curnum);
1905 return v;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001906
1907 Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001908 Py_XDECREF(low);
1909 Py_XDECREF(high);
1910 Py_XDECREF(step);
1911 Py_DECREF(zero);
1912 Py_XDECREF(curnum);
1913 Py_XDECREF(v);
1914 return NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001915}
1916
Guido van Rossum124eff01999-02-23 16:11:01 +00001917/* Return number of items in range/xrange (lo, hi, step). step > 0
1918 * required. Return a value < 0 if & only if the true value is too
1919 * large to fit in a signed long.
1920 */
1921static long
Thomas Wouterse28c2962000-07-23 22:21:32 +00001922get_len_of_range(long lo, long hi, long step)
Guido van Rossum124eff01999-02-23 16:11:01 +00001923{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001924 /* -------------------------------------------------------------
1925 If lo >= hi, the range is empty.
1926 Else if n values are in the range, the last one is
1927 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1928 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1929 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1930 the RHS is non-negative and so truncation is the same as the
1931 floor. Letting M be the largest positive long, the worst case
1932 for the RHS numerator is hi=M, lo=-M-1, and then
1933 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1934 precision to compute the RHS exactly.
1935 ---------------------------------------------------------------*/
1936 long n = 0;
1937 if (lo < hi) {
1938 unsigned long uhi = (unsigned long)hi;
1939 unsigned long ulo = (unsigned long)lo;
1940 unsigned long diff = uhi - ulo - 1;
1941 n = (long)(diff / (unsigned long)step + 1);
1942 }
1943 return n;
Guido van Rossum124eff01999-02-23 16:11:01 +00001944}
1945
Guido van Rossum79f25d91997-04-29 20:08:16 +00001946static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001947builtin_range(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001948{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001949 long ilow = 0, ihigh = 0, istep = 1;
1950 long bign;
1951 Py_ssize_t i, n;
Guido van Rossum124eff01999-02-23 16:11:01 +00001952
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001953 PyObject *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001954
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001955 if (PyTuple_Size(args) <= 1) {
1956 if (!PyArg_ParseTuple(args,
1957 "l;range() requires 1-3 int arguments",
1958 &ihigh)) {
1959 PyErr_Clear();
1960 return handle_range_longs(self, args);
1961 }
1962 }
1963 else {
1964 if (!PyArg_ParseTuple(args,
1965 "ll|l;range() requires 1-3 int arguments",
1966 &ilow, &ihigh, &istep)) {
1967 PyErr_Clear();
1968 return handle_range_longs(self, args);
1969 }
1970 }
1971 if (istep == 0) {
1972 PyErr_SetString(PyExc_ValueError,
1973 "range() step argument must not be zero");
1974 return NULL;
1975 }
1976 if (istep > 0)
1977 bign = get_len_of_range(ilow, ihigh, istep);
1978 else
1979 bign = get_len_of_range(ihigh, ilow, -istep);
1980 n = (Py_ssize_t)bign;
1981 if (bign < 0 || (long)n != bign) {
1982 PyErr_SetString(PyExc_OverflowError,
1983 "range() result has too many items");
1984 return NULL;
1985 }
1986 v = PyList_New(n);
1987 if (v == NULL)
1988 return NULL;
1989 for (i = 0; i < n; i++) {
1990 PyObject *w = PyInt_FromLong(ilow);
1991 if (w == NULL) {
1992 Py_DECREF(v);
1993 return NULL;
1994 }
1995 PyList_SET_ITEM(v, i, w);
1996 ilow += istep;
1997 }
1998 return v;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001999}
2000
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002001PyDoc_STRVAR(range_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002002"range([start,] stop[, step]) -> list of integers\n\
2003\n\
2004Return a list containing an arithmetic progression of integers.\n\
2005range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
2006When step is given, it specifies the increment (or decrement).\n\
2007For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002008These are exactly the valid indices for a list of 4 elements.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002009
2010
Guido van Rossum79f25d91997-04-29 20:08:16 +00002011static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002012builtin_raw_input(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002013{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002014 PyObject *v = NULL;
2015 PyObject *fin = PySys_GetObject("stdin");
2016 PyObject *fout = PySys_GetObject("stdout");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002017
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002018 if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
2019 return NULL;
Martin v. Löwis31d2df52002-08-14 15:46:02 +00002020
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002021 if (fin == NULL) {
2022 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
2023 return NULL;
2024 }
2025 if (fout == NULL) {
2026 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
2027 return NULL;
2028 }
2029 if (PyFile_SoftSpace(fout, 0)) {
2030 if (PyFile_WriteString(" ", fout) != 0)
2031 return NULL;
2032 }
2033 if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
2034 && isatty(fileno(PyFile_AsFile(fin)))
2035 && isatty(fileno(PyFile_AsFile(fout)))) {
2036 PyObject *po;
2037 char *prompt;
2038 char *s;
2039 PyObject *result;
2040 if (v != NULL) {
2041 po = PyObject_Str(v);
2042 if (po == NULL)
2043 return NULL;
2044 prompt = PyString_AsString(po);
2045 if (prompt == NULL)
2046 return NULL;
2047 }
2048 else {
2049 po = NULL;
2050 prompt = "";
2051 }
2052 s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
2053 prompt);
2054 Py_XDECREF(po);
2055 if (s == NULL) {
2056 if (!PyErr_Occurred())
2057 PyErr_SetNone(PyExc_KeyboardInterrupt);
2058 return NULL;
2059 }
2060 if (*s == '\0') {
2061 PyErr_SetNone(PyExc_EOFError);
2062 result = NULL;
2063 }
2064 else { /* strip trailing '\n' */
2065 size_t len = strlen(s);
2066 if (len > PY_SSIZE_T_MAX) {
2067 PyErr_SetString(PyExc_OverflowError,
2068 "[raw_]input: input too long");
2069 result = NULL;
2070 }
2071 else {
2072 result = PyString_FromStringAndSize(s, len-1);
2073 }
2074 }
2075 PyMem_FREE(s);
2076 return result;
2077 }
2078 if (v != NULL) {
2079 if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
2080 return NULL;
2081 }
2082 return PyFile_GetLine(fin, -1);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002083}
2084
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002085PyDoc_STRVAR(raw_input_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002086"raw_input([prompt]) -> string\n\
2087\n\
2088Read a string from standard input. The trailing newline is stripped.\n\
2089If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
2090On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002091is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002092
2093
Guido van Rossum79f25d91997-04-29 20:08:16 +00002094static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002095builtin_reduce(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002096{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002097 static PyObject *functools_reduce = NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002098
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002099 if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
2100 "use functools.reduce()", 1) < 0)
2101 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +00002102
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002103 if (functools_reduce == NULL) {
2104 PyObject *functools = PyImport_ImportModule("functools");
2105 if (functools == NULL)
2106 return NULL;
2107 functools_reduce = PyObject_GetAttrString(functools, "reduce");
2108 Py_DECREF(functools);
2109 if (functools_reduce == NULL)
2110 return NULL;
2111 }
2112 return PyObject_Call(functools_reduce, args, NULL);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002113}
2114
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002115PyDoc_STRVAR(reduce_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002116"reduce(function, sequence[, initial]) -> value\n\
2117\n\
2118Apply a function of two arguments cumulatively to the items of a sequence,\n\
2119from left to right, so as to reduce the sequence to a single value.\n\
2120For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
2121((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
2122of the sequence in the calculation, and serves as a default when the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002123sequence is empty.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002124
2125
Guido van Rossum79f25d91997-04-29 20:08:16 +00002126static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002127builtin_reload(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002128{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002129 if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
2130 1) < 0)
2131 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +00002132
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002133 return PyImport_ReloadModule(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002134}
2135
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002136PyDoc_STRVAR(reload_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002137"reload(module) -> module\n\
2138\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002139Reload the module. The module must have been successfully imported before.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002140
2141
Guido van Rossum79f25d91997-04-29 20:08:16 +00002142static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002143builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00002144{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002145 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002146}
2147
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002148PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002149"repr(object) -> string\n\
2150\n\
2151Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002152For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002153
2154
Guido van Rossum79f25d91997-04-29 20:08:16 +00002155static PyObject *
Georg Brandlccadf842006-03-31 18:54:53 +00002156builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002157{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002158 double x;
2159 PyObject *o_ndigits = NULL;
2160 Py_ssize_t ndigits;
2161 static char *kwlist[] = {"number", "ndigits", 0};
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002162
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002163 if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|O:round",
2164 kwlist, &x, &o_ndigits))
2165 return NULL;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002166
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002167 if (o_ndigits == NULL) {
2168 /* second argument defaults to 0 */
2169 ndigits = 0;
2170 }
2171 else {
2172 /* interpret 2nd argument as a Py_ssize_t; clip on overflow */
2173 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
2174 if (ndigits == -1 && PyErr_Occurred())
2175 return NULL;
2176 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002177
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002178 /* nans, infinities and zeros round to themselves */
2179 if (!Py_IS_FINITE(x) || x == 0.0)
2180 return PyFloat_FromDouble(x);
Mark Dickinsonbce78372009-11-24 10:54:58 +00002181
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002182 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
2183 always rounds to itself. For ndigits < NDIGITS_MIN, x always
2184 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002185#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
2186#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002187 if (ndigits > NDIGITS_MAX)
2188 /* return x */
2189 return PyFloat_FromDouble(x);
2190 else if (ndigits < NDIGITS_MIN)
2191 /* return 0.0, but with sign of x */
2192 return PyFloat_FromDouble(0.0*x);
2193 else
2194 /* finite x, and ndigits is not unreasonably large */
2195 /* _Py_double_round is defined in floatobject.c */
2196 return _Py_double_round(x, (int)ndigits);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002197#undef NDIGITS_MAX
2198#undef NDIGITS_MIN
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002199}
2200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002201PyDoc_STRVAR(round_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002202"round(number[, ndigits]) -> floating point number\n\
2203\n\
2204Round a number to a given precision in decimal digits (default 0 digits).\n\
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +00002205This always returns a floating point number. Precision may be negative.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002206
Raymond Hettinger64958a12003-12-17 20:43:33 +00002207static PyObject *
2208builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2209{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002210 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
2211 PyObject *callable;
2212 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
2213 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002214
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002215 /* args 1-4 should match listsort in Objects/listobject.c */
2216 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
2217 kwlist, &seq, &compare, &keyfunc, &reverse))
2218 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002219
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002220 newlist = PySequence_List(seq);
2221 if (newlist == NULL)
2222 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002223
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002224 callable = PyObject_GetAttrString(newlist, "sort");
2225 if (callable == NULL) {
2226 Py_DECREF(newlist);
2227 return NULL;
2228 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002229
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002230 newargs = PyTuple_GetSlice(args, 1, 4);
2231 if (newargs == NULL) {
2232 Py_DECREF(newlist);
2233 Py_DECREF(callable);
2234 return NULL;
2235 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00002236
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002237 v = PyObject_Call(callable, newargs, kwds);
2238 Py_DECREF(newargs);
2239 Py_DECREF(callable);
2240 if (v == NULL) {
2241 Py_DECREF(newlist);
2242 return NULL;
2243 }
2244 Py_DECREF(v);
2245 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002246}
2247
2248PyDoc_STRVAR(sorted_doc,
2249"sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002250
Guido van Rossum79f25d91997-04-29 20:08:16 +00002251static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002252builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002253{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002254 PyObject *v = NULL;
2255 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002256
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002257 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2258 return NULL;
2259 if (v == NULL) {
2260 d = PyEval_GetLocals();
2261 if (d == NULL) {
2262 if (!PyErr_Occurred())
2263 PyErr_SetString(PyExc_SystemError,
2264 "vars(): no locals!?");
2265 }
2266 else
2267 Py_INCREF(d);
2268 }
2269 else {
2270 d = PyObject_GetAttrString(v, "__dict__");
2271 if (d == NULL) {
2272 PyErr_SetString(PyExc_TypeError,
2273 "vars() argument must have __dict__ attribute");
2274 return NULL;
2275 }
2276 }
2277 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002278}
2279
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002280PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002281"vars([object]) -> dictionary\n\
2282\n\
2283Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002284With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002285
Alex Martellia70b1912003-04-22 08:12:33 +00002286
2287static PyObject*
2288builtin_sum(PyObject *self, PyObject *args)
2289{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002290 PyObject *seq;
2291 PyObject *result = NULL;
2292 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002293
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002294 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
2295 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002296
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002297 iter = PyObject_GetIter(seq);
2298 if (iter == NULL)
2299 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002300
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002301 if (result == NULL) {
2302 result = PyInt_FromLong(0);
2303 if (result == NULL) {
2304 Py_DECREF(iter);
2305 return NULL;
2306 }
2307 } else {
2308 /* reject string values for 'start' parameter */
2309 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
2310 PyErr_SetString(PyExc_TypeError,
2311 "sum() can't sum strings [use ''.join(seq) instead]");
2312 Py_DECREF(iter);
2313 return NULL;
2314 }
2315 Py_INCREF(result);
2316 }
Alex Martellia70b1912003-04-22 08:12:33 +00002317
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002318#ifndef SLOW_SUM
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002319 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2320 Assumes all inputs are the same type. If the assumption fails, default
2321 to the more general routine.
2322 */
2323 if (PyInt_CheckExact(result)) {
2324 long i_result = PyInt_AS_LONG(result);
2325 Py_DECREF(result);
2326 result = NULL;
2327 while(result == NULL) {
2328 item = PyIter_Next(iter);
2329 if (item == NULL) {
2330 Py_DECREF(iter);
2331 if (PyErr_Occurred())
2332 return NULL;
2333 return PyInt_FromLong(i_result);
2334 }
2335 if (PyInt_CheckExact(item)) {
2336 long b = PyInt_AS_LONG(item);
2337 long x = i_result + b;
2338 if ((x^i_result) >= 0 || (x^b) >= 0) {
2339 i_result = x;
2340 Py_DECREF(item);
2341 continue;
2342 }
2343 }
2344 /* Either overflowed or is not an int. Restore real objects and process normally */
2345 result = PyInt_FromLong(i_result);
2346 temp = PyNumber_Add(result, item);
2347 Py_DECREF(result);
2348 Py_DECREF(item);
2349 result = temp;
2350 if (result == NULL) {
2351 Py_DECREF(iter);
2352 return NULL;
2353 }
2354 }
2355 }
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002356
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002357 if (PyFloat_CheckExact(result)) {
2358 double f_result = PyFloat_AS_DOUBLE(result);
2359 Py_DECREF(result);
2360 result = NULL;
2361 while(result == NULL) {
2362 item = PyIter_Next(iter);
2363 if (item == NULL) {
2364 Py_DECREF(iter);
2365 if (PyErr_Occurred())
2366 return NULL;
2367 return PyFloat_FromDouble(f_result);
2368 }
2369 if (PyFloat_CheckExact(item)) {
2370 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2371 f_result += PyFloat_AS_DOUBLE(item);
2372 PyFPE_END_PROTECT(f_result)
2373 Py_DECREF(item);
2374 continue;
2375 }
2376 if (PyInt_CheckExact(item)) {
2377 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2378 f_result += (double)PyInt_AS_LONG(item);
2379 PyFPE_END_PROTECT(f_result)
2380 Py_DECREF(item);
2381 continue;
2382 }
2383 result = PyFloat_FromDouble(f_result);
2384 temp = PyNumber_Add(result, item);
2385 Py_DECREF(result);
2386 Py_DECREF(item);
2387 result = temp;
2388 if (result == NULL) {
2389 Py_DECREF(iter);
2390 return NULL;
2391 }
2392 }
2393 }
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002394#endif
2395
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002396 for(;;) {
2397 item = PyIter_Next(iter);
2398 if (item == NULL) {
2399 /* error, or end-of-sequence */
2400 if (PyErr_Occurred()) {
2401 Py_DECREF(result);
2402 result = NULL;
2403 }
2404 break;
2405 }
2406 /* It's tempting to use PyNumber_InPlaceAdd instead of
2407 PyNumber_Add here, to avoid quadratic running time
2408 when doing 'sum(list_of_lists, [])'. However, this
2409 would produce a change in behaviour: a snippet like
Mark Dickinson0e0e2152009-10-26 14:18:44 +00002410
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002411 empty = []
2412 sum([[x] for x in range(10)], empty)
Mark Dickinson0e0e2152009-10-26 14:18:44 +00002413
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002414 would change the value of empty. */
2415 temp = PyNumber_Add(result, item);
2416 Py_DECREF(result);
2417 Py_DECREF(item);
2418 result = temp;
2419 if (result == NULL)
2420 break;
2421 }
2422 Py_DECREF(iter);
2423 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002424}
2425
2426PyDoc_STRVAR(sum_doc,
Georg Brandl8134d062006-10-12 12:33:07 +00002427"sum(sequence[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002428\n\
2429Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
Georg Brandl8134d062006-10-12 12:33:07 +00002430of parameter 'start' (which defaults to 0). When the sequence is\n\
2431empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002432
2433
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002434static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002435builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002436{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002437 PyObject *inst;
2438 PyObject *cls;
2439 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002440
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002441 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2442 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002443
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002444 retval = PyObject_IsInstance(inst, cls);
2445 if (retval < 0)
2446 return NULL;
2447 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002448}
2449
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002450PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002451"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002452\n\
2453Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002454With a type as second argument, return whether that is the object's type.\n\
2455The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002456isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002457
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002458
2459static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002460builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002461{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002462 PyObject *derived;
2463 PyObject *cls;
2464 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002465
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002466 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2467 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002468
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002469 retval = PyObject_IsSubclass(derived, cls);
2470 if (retval < 0)
2471 return NULL;
2472 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002473}
2474
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002475PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002476"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002477\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002478Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2479When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2480is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002481
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002482
Barry Warsawbd599b52000-08-03 15:45:29 +00002483static PyObject*
2484builtin_zip(PyObject *self, PyObject *args)
2485{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002486 PyObject *ret;
2487 const Py_ssize_t itemsize = PySequence_Length(args);
2488 Py_ssize_t i;
2489 PyObject *itlist; /* tuple of iterators */
2490 Py_ssize_t len; /* guess at result length */
Barry Warsawbd599b52000-08-03 15:45:29 +00002491
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002492 if (itemsize == 0)
2493 return PyList_New(0);
Raymond Hettingereaef6152003-08-02 07:42:57 +00002494
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002495 /* args must be a tuple */
2496 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002497
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002498 /* Guess at result length: the shortest of the input lengths.
2499 If some argument refuses to say, we refuse to guess too, lest
2500 an argument like xrange(sys.maxint) lead us astray.*/
2501 len = -1; /* unknown */
2502 for (i = 0; i < itemsize; ++i) {
2503 PyObject *item = PyTuple_GET_ITEM(args, i);
2504 Py_ssize_t thislen = _PyObject_LengthHint(item, -2);
2505 if (thislen < 0) {
2506 if (thislen == -1)
2507 return NULL;
2508 len = -1;
2509 break;
2510 }
2511 else if (len < 0 || thislen < len)
2512 len = thislen;
2513 }
Tim Peters67d687a2002-04-29 21:27:32 +00002514
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002515 /* allocate result list */
2516 if (len < 0)
2517 len = 10; /* arbitrary */
2518 if ((ret = PyList_New(len)) == NULL)
2519 return NULL;
Barry Warsawbd599b52000-08-03 15:45:29 +00002520
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002521 /* obtain iterators */
2522 itlist = PyTuple_New(itemsize);
2523 if (itlist == NULL)
2524 goto Fail_ret;
2525 for (i = 0; i < itemsize; ++i) {
2526 PyObject *item = PyTuple_GET_ITEM(args, i);
2527 PyObject *it = PyObject_GetIter(item);
2528 if (it == NULL) {
2529 if (PyErr_ExceptionMatches(PyExc_TypeError))
2530 PyErr_Format(PyExc_TypeError,
2531 "zip argument #%zd must support iteration",
2532 i+1);
2533 goto Fail_ret_itlist;
2534 }
2535 PyTuple_SET_ITEM(itlist, i, it);
2536 }
Barry Warsawbd599b52000-08-03 15:45:29 +00002537
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002538 /* build result into ret list */
2539 for (i = 0; ; ++i) {
2540 int j;
2541 PyObject *next = PyTuple_New(itemsize);
2542 if (!next)
2543 goto Fail_ret_itlist;
Tim Peters8572b4f2001-05-06 01:05:02 +00002544
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002545 for (j = 0; j < itemsize; j++) {
2546 PyObject *it = PyTuple_GET_ITEM(itlist, j);
2547 PyObject *item = PyIter_Next(it);
2548 if (!item) {
2549 if (PyErr_Occurred()) {
2550 Py_DECREF(ret);
2551 ret = NULL;
2552 }
2553 Py_DECREF(next);
2554 Py_DECREF(itlist);
2555 goto Done;
2556 }
2557 PyTuple_SET_ITEM(next, j, item);
2558 }
Tim Peters8572b4f2001-05-06 01:05:02 +00002559
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002560 if (i < len)
2561 PyList_SET_ITEM(ret, i, next);
2562 else {
2563 int status = PyList_Append(ret, next);
2564 Py_DECREF(next);
2565 ++len;
2566 if (status < 0)
2567 goto Fail_ret_itlist;
2568 }
2569 }
Tim Peters8572b4f2001-05-06 01:05:02 +00002570
Tim Peters67d687a2002-04-29 21:27:32 +00002571Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002572 if (ret != NULL && i < len) {
2573 /* The list is too big. */
2574 if (PyList_SetSlice(ret, i, len, NULL) < 0)
2575 return NULL;
2576 }
2577 return ret;
Tim Peters67d687a2002-04-29 21:27:32 +00002578
Tim Peters8572b4f2001-05-06 01:05:02 +00002579Fail_ret_itlist:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002580 Py_DECREF(itlist);
Tim Peters8572b4f2001-05-06 01:05:02 +00002581Fail_ret:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002582 Py_DECREF(ret);
2583 return NULL;
Barry Warsawbd599b52000-08-03 15:45:29 +00002584}
2585
2586
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002587PyDoc_STRVAR(zip_doc,
Barry Warsawbd599b52000-08-03 15:45:29 +00002588"zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2589\n\
2590Return a list of tuples, where each tuple contains the i-th element\n\
2591from each of the argument sequences. The returned list is truncated\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002592in length to the length of the shortest argument sequence.");
Barry Warsawbd599b52000-08-03 15:45:29 +00002593
2594
Guido van Rossum79f25d91997-04-29 20:08:16 +00002595static PyMethodDef builtin_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002596 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2597 {"abs", builtin_abs, METH_O, abs_doc},
2598 {"all", builtin_all, METH_O, all_doc},
2599 {"any", builtin_any, METH_O, any_doc},
2600 {"apply", builtin_apply, METH_VARARGS, apply_doc},
2601 {"bin", builtin_bin, METH_O, bin_doc},
2602 {"callable", builtin_callable, METH_O, callable_doc},
2603 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2604 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
2605 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
2606 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2607 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2608 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2609 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2610 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2611 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
2612 {"filter", builtin_filter, METH_VARARGS, filter_doc},
2613 {"format", builtin_format, METH_VARARGS, format_doc},
2614 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2615 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2616 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2617 {"hash", builtin_hash, METH_O, hash_doc},
2618 {"hex", builtin_hex, METH_O, hex_doc},
2619 {"id", builtin_id, METH_O, id_doc},
2620 {"input", builtin_input, METH_VARARGS, input_doc},
2621 {"intern", builtin_intern, METH_VARARGS, intern_doc},
2622 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2623 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2624 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2625 {"len", builtin_len, METH_O, len_doc},
2626 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2627 {"map", builtin_map, METH_VARARGS, map_doc},
2628 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2629 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2630 {"next", builtin_next, METH_VARARGS, next_doc},
2631 {"oct", builtin_oct, METH_O, oct_doc},
2632 {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
2633 {"ord", builtin_ord, METH_O, ord_doc},
2634 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2635 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2636 {"range", builtin_range, METH_VARARGS, range_doc},
2637 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
2638 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
2639 {"reload", builtin_reload, METH_O, reload_doc},
2640 {"repr", builtin_repr, METH_O, repr_doc},
2641 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2642 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2643 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2644 {"sum", builtin_sum, METH_VARARGS, sum_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002645#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002646 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002647#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002648 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2649 {"zip", builtin_zip, METH_VARARGS, zip_doc},
2650 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002651};
2652
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002653PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002654"Built-in functions, exceptions, and other objects.\n\
2655\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002656Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002657
Guido van Rossum25ce5661997-08-02 03:10:38 +00002658PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002659_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002660{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002661 PyObject *mod, *dict, *debug;
2662 mod = Py_InitModule4("__builtin__", builtin_methods,
2663 builtin_doc, (PyObject *)NULL,
2664 PYTHON_API_VERSION);
2665 if (mod == NULL)
2666 return NULL;
2667 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002668
Tim Peters7571a0f2003-03-23 17:52:28 +00002669#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002670 /* __builtin__ exposes a number of statically allocated objects
2671 * that, before this code was added in 2.3, never showed up in
2672 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2673 * result, programs leaking references to None and False (etc)
2674 * couldn't be diagnosed by examining sys.getobjects(0).
2675 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002676#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2677#else
2678#define ADD_TO_ALL(OBJECT) (void)0
2679#endif
2680
Tim Peters4b7625e2001-09-13 21:37:17 +00002681#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002682 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2683 return NULL; \
2684 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002685
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002686 SETBUILTIN("None", Py_None);
2687 SETBUILTIN("Ellipsis", Py_Ellipsis);
2688 SETBUILTIN("NotImplemented", Py_NotImplemented);
2689 SETBUILTIN("False", Py_False);
2690 SETBUILTIN("True", Py_True);
2691 SETBUILTIN("basestring", &PyBaseString_Type);
2692 SETBUILTIN("bool", &PyBool_Type);
2693 SETBUILTIN("memoryview", &PyMemoryView_Type);
2694 SETBUILTIN("bytearray", &PyByteArray_Type);
2695 SETBUILTIN("bytes", &PyString_Type);
2696 SETBUILTIN("buffer", &PyBuffer_Type);
2697 SETBUILTIN("classmethod", &PyClassMethod_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002698#ifndef WITHOUT_COMPLEX
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002699 SETBUILTIN("complex", &PyComplex_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002700#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002701 SETBUILTIN("dict", &PyDict_Type);
2702 SETBUILTIN("enumerate", &PyEnum_Type);
2703 SETBUILTIN("file", &PyFile_Type);
2704 SETBUILTIN("float", &PyFloat_Type);
2705 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2706 SETBUILTIN("property", &PyProperty_Type);
2707 SETBUILTIN("int", &PyInt_Type);
2708 SETBUILTIN("list", &PyList_Type);
2709 SETBUILTIN("long", &PyLong_Type);
2710 SETBUILTIN("object", &PyBaseObject_Type);
2711 SETBUILTIN("reversed", &PyReversed_Type);
2712 SETBUILTIN("set", &PySet_Type);
2713 SETBUILTIN("slice", &PySlice_Type);
2714 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2715 SETBUILTIN("str", &PyString_Type);
2716 SETBUILTIN("super", &PySuper_Type);
2717 SETBUILTIN("tuple", &PyTuple_Type);
2718 SETBUILTIN("type", &PyType_Type);
2719 SETBUILTIN("xrange", &PyRange_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002720#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002721 SETBUILTIN("unicode", &PyUnicode_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002722#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002723 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2724 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2725 Py_XDECREF(debug);
2726 return NULL;
2727 }
2728 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002729
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002730 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002731#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002732#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002733}
2734
Guido van Rossume77a7571993-11-03 15:01:26 +00002735/* Helper for filter(): filter a tuple through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002736
Guido van Rossum79f25d91997-04-29 20:08:16 +00002737static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002738filtertuple(PyObject *func, PyObject *tuple)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002739{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002740 PyObject *result;
2741 Py_ssize_t i, j;
2742 Py_ssize_t len = PyTuple_Size(tuple);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002743
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002744 if (len == 0) {
2745 if (PyTuple_CheckExact(tuple))
2746 Py_INCREF(tuple);
2747 else
2748 tuple = PyTuple_New(0);
2749 return tuple;
2750 }
Guido van Rossumb7b45621995-08-04 04:07:45 +00002751
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002752 if ((result = PyTuple_New(len)) == NULL)
2753 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002754
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002755 for (i = j = 0; i < len; ++i) {
2756 PyObject *item, *good;
2757 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002758
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002759 if (tuple->ob_type->tp_as_sequence &&
2760 tuple->ob_type->tp_as_sequence->sq_item) {
2761 item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
2762 if (item == NULL)
2763 goto Fail_1;
2764 } else {
2765 PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
2766 goto Fail_1;
2767 }
2768 if (func == Py_None) {
2769 Py_INCREF(item);
2770 good = item;
2771 }
2772 else {
2773 PyObject *arg = PyTuple_Pack(1, item);
2774 if (arg == NULL) {
2775 Py_DECREF(item);
2776 goto Fail_1;
2777 }
2778 good = PyEval_CallObject(func, arg);
2779 Py_DECREF(arg);
2780 if (good == NULL) {
2781 Py_DECREF(item);
2782 goto Fail_1;
2783 }
2784 }
2785 ok = PyObject_IsTrue(good);
2786 Py_DECREF(good);
2787 if (ok) {
2788 if (PyTuple_SetItem(result, j++, item) < 0)
2789 goto Fail_1;
2790 }
2791 else
2792 Py_DECREF(item);
2793 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002794
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002795 if (_PyTuple_Resize(&result, j) < 0)
2796 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002797
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002798 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002799
Guido van Rossum12d12c51993-10-26 17:58:25 +00002800Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002801 Py_DECREF(result);
2802 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002803}
2804
2805
Guido van Rossume77a7571993-11-03 15:01:26 +00002806/* Helper for filter(): filter a string through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002807
Guido van Rossum79f25d91997-04-29 20:08:16 +00002808static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002809filterstring(PyObject *func, PyObject *strobj)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002810{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002811 PyObject *result;
2812 Py_ssize_t i, j;
2813 Py_ssize_t len = PyString_Size(strobj);
2814 Py_ssize_t outlen = len;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002815
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002816 if (func == Py_None) {
2817 /* If it's a real string we can return the original,
2818 * as no character is ever false and __getitem__
2819 * does return this character. If it's a subclass
2820 * we must go through the __getitem__ loop */
2821 if (PyString_CheckExact(strobj)) {
2822 Py_INCREF(strobj);
2823 return strobj;
2824 }
2825 }
2826 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2827 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002828
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002829 for (i = j = 0; i < len; ++i) {
2830 PyObject *item;
2831 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002832
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002833 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2834 if (item == NULL)
2835 goto Fail_1;
2836 if (func==Py_None) {
2837 ok = 1;
2838 } else {
2839 PyObject *arg, *good;
2840 arg = PyTuple_Pack(1, item);
2841 if (arg == NULL) {
2842 Py_DECREF(item);
2843 goto Fail_1;
2844 }
2845 good = PyEval_CallObject(func, arg);
2846 Py_DECREF(arg);
2847 if (good == NULL) {
2848 Py_DECREF(item);
2849 goto Fail_1;
2850 }
2851 ok = PyObject_IsTrue(good);
2852 Py_DECREF(good);
2853 }
2854 if (ok) {
2855 Py_ssize_t reslen;
2856 if (!PyString_Check(item)) {
2857 PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
2858 " __getitem__ returned different type");
2859 Py_DECREF(item);
2860 goto Fail_1;
2861 }
2862 reslen = PyString_GET_SIZE(item);
2863 if (reslen == 1) {
2864 PyString_AS_STRING(result)[j++] =
2865 PyString_AS_STRING(item)[0];
2866 } else {
2867 /* do we need more space? */
2868 Py_ssize_t need = j;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002869
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002870 /* calculate space requirements while checking for overflow */
2871 if (need > PY_SSIZE_T_MAX - reslen) {
2872 Py_DECREF(item);
2873 goto Fail_1;
2874 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002875
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002876 need += reslen;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002877
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002878 if (need > PY_SSIZE_T_MAX - len) {
2879 Py_DECREF(item);
2880 goto Fail_1;
2881 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002882
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002883 need += len;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002884
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002885 if (need <= i) {
2886 Py_DECREF(item);
2887 goto Fail_1;
2888 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002889
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002890 need = need - i - 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002891
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002892 assert(need >= 0);
2893 assert(outlen >= 0);
Gregory P. Smith9d534572008-06-11 07:41:16 +00002894
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002895 if (need > outlen) {
2896 /* overallocate, to avoid reallocations */
2897 if (outlen > PY_SSIZE_T_MAX / 2) {
2898 Py_DECREF(item);
2899 return NULL;
2900 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002901
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002902 if (need<2*outlen) {
2903 need = 2*outlen;
2904 }
2905 if (_PyString_Resize(&result, need)) {
2906 Py_DECREF(item);
2907 return NULL;
2908 }
2909 outlen = need;
2910 }
2911 memcpy(
2912 PyString_AS_STRING(result) + j,
2913 PyString_AS_STRING(item),
2914 reslen
2915 );
2916 j += reslen;
2917 }
2918 }
2919 Py_DECREF(item);
2920 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002921
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002922 if (j < outlen)
2923 _PyString_Resize(&result, j);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002924
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002925 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002926
Guido van Rossum12d12c51993-10-26 17:58:25 +00002927Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002928 Py_DECREF(result);
2929 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002930}
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002931
2932#ifdef Py_USING_UNICODE
2933/* Helper for filter(): filter a Unicode object through a function */
2934
2935static PyObject *
2936filterunicode(PyObject *func, PyObject *strobj)
2937{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002938 PyObject *result;
2939 register Py_ssize_t i, j;
2940 Py_ssize_t len = PyUnicode_GetSize(strobj);
2941 Py_ssize_t outlen = len;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002942
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002943 if (func == Py_None) {
2944 /* If it's a real string we can return the original,
2945 * as no character is ever false and __getitem__
2946 * does return this character. If it's a subclass
2947 * we must go through the __getitem__ loop */
2948 if (PyUnicode_CheckExact(strobj)) {
2949 Py_INCREF(strobj);
2950 return strobj;
2951 }
2952 }
2953 if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
2954 return NULL;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002955
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002956 for (i = j = 0; i < len; ++i) {
2957 PyObject *item, *arg, *good;
2958 int ok;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002959
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002960 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2961 if (item == NULL)
2962 goto Fail_1;
2963 if (func == Py_None) {
2964 ok = 1;
2965 } else {
2966 arg = PyTuple_Pack(1, item);
2967 if (arg == NULL) {
2968 Py_DECREF(item);
2969 goto Fail_1;
2970 }
2971 good = PyEval_CallObject(func, arg);
2972 Py_DECREF(arg);
2973 if (good == NULL) {
2974 Py_DECREF(item);
2975 goto Fail_1;
2976 }
2977 ok = PyObject_IsTrue(good);
2978 Py_DECREF(good);
2979 }
2980 if (ok) {
2981 Py_ssize_t reslen;
2982 if (!PyUnicode_Check(item)) {
2983 PyErr_SetString(PyExc_TypeError,
2984 "can't filter unicode to unicode:"
2985 " __getitem__ returned different type");
2986 Py_DECREF(item);
2987 goto Fail_1;
2988 }
2989 reslen = PyUnicode_GET_SIZE(item);
2990 if (reslen == 1)
2991 PyUnicode_AS_UNICODE(result)[j++] =
2992 PyUnicode_AS_UNICODE(item)[0];
2993 else {
2994 /* do we need more space? */
2995 Py_ssize_t need = j + reslen + len - i - 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002996
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002997 /* check that didnt overflow */
2998 if ((j > PY_SSIZE_T_MAX - reslen) ||
2999 ((j + reslen) > PY_SSIZE_T_MAX - len) ||
3000 ((j + reslen + len) < i) ||
3001 ((j + reslen + len - i) <= 0)) {
3002 Py_DECREF(item);
3003 return NULL;
3004 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00003005
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003006 assert(need >= 0);
3007 assert(outlen >= 0);
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003008
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003009 if (need > outlen) {
3010 /* overallocate,
3011 to avoid reallocations */
3012 if (need < 2 * outlen) {
3013 if (outlen > PY_SSIZE_T_MAX / 2) {
3014 Py_DECREF(item);
3015 return NULL;
3016 } else {
3017 need = 2 * outlen;
3018 }
3019 }
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003020
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003021 if (PyUnicode_Resize(
3022 &result, need) < 0) {
3023 Py_DECREF(item);
3024 goto Fail_1;
3025 }
3026 outlen = need;
3027 }
3028 memcpy(PyUnicode_AS_UNICODE(result) + j,
3029 PyUnicode_AS_UNICODE(item),
3030 reslen*sizeof(Py_UNICODE));
3031 j += reslen;
3032 }
3033 }
3034 Py_DECREF(item);
3035 }
3036
3037 if (j < outlen)
3038 PyUnicode_Resize(&result, j);
3039
3040 return result;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003041
3042Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003043 Py_DECREF(result);
3044 return NULL;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003045}
3046#endif