blob: f03e48892e45a466c8c5b365b04ee4765075d46f [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\
Ezio Melotti94bf6972013-02-15 23:35:14 +0200123Return True if bool(x) is True for all values x in the iterable.\n\
124If the iterable is empty, return True.");
Raymond Hettinger96229b12005-03-11 06:49:40 +0000125
126static PyObject *
127builtin_any(PyObject *self, PyObject *v)
128{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000129 PyObject *it, *item;
130 PyObject *(*iternext)(PyObject *);
131 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000132
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000133 it = PyObject_GetIter(v);
134 if (it == NULL)
135 return NULL;
136 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000137
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000138 for (;;) {
139 item = iternext(it);
140 if (item == NULL)
141 break;
142 cmp = PyObject_IsTrue(item);
143 Py_DECREF(item);
144 if (cmp < 0) {
145 Py_DECREF(it);
146 return NULL;
147 }
148 if (cmp == 1) {
149 Py_DECREF(it);
150 Py_RETURN_TRUE;
151 }
152 }
153 Py_DECREF(it);
154 if (PyErr_Occurred()) {
155 if (PyErr_ExceptionMatches(PyExc_StopIteration))
156 PyErr_Clear();
157 else
158 return NULL;
159 }
160 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000161}
162
163PyDoc_STRVAR(any_doc,
164"any(iterable) -> bool\n\
165\n\
Ezio Melotti94bf6972013-02-15 23:35:14 +0200166Return True if bool(x) is True for any x in the iterable.\n\
167If the iterable is empty, return False.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000168
Guido van Rossum79f25d91997-04-29 20:08:16 +0000169static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000170builtin_apply(PyObject *self, PyObject *args)
Guido van Rossumc02e15c1991-12-16 13:03:00 +0000171{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000172 PyObject *func, *alist = NULL, *kwdict = NULL;
173 PyObject *t = NULL, *retval = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000174
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000175 if (PyErr_WarnPy3k("apply() not supported in 3.x; "
176 "use func(*args, **kwargs)", 1) < 0)
177 return NULL;
Neal Norwitz8b2bfbc2007-05-23 06:35:32 +0000178
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000179 if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))
180 return NULL;
181 if (alist != NULL) {
182 if (!PyTuple_Check(alist)) {
183 if (!PySequence_Check(alist)) {
184 PyErr_Format(PyExc_TypeError,
185 "apply() arg 2 expected sequence, found %s",
186 alist->ob_type->tp_name);
187 return NULL;
188 }
189 t = PySequence_Tuple(alist);
190 if (t == NULL)
191 return NULL;
192 alist = t;
193 }
194 }
195 if (kwdict != NULL && !PyDict_Check(kwdict)) {
196 PyErr_Format(PyExc_TypeError,
197 "apply() arg 3 expected dictionary, found %s",
198 kwdict->ob_type->tp_name);
199 goto finally;
200 }
201 retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
Barry Warsaw968f8cb1998-10-01 15:33:12 +0000202 finally:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000203 Py_XDECREF(t);
204 return retval;
Guido van Rossumc02e15c1991-12-16 13:03:00 +0000205}
206
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000207PyDoc_STRVAR(apply_doc,
Fred Drakef1fbc622001-01-12 17:05:05 +0000208"apply(object[, args[, kwargs]]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000209\n\
Fred Drake7b912121999-12-23 14:16:55 +0000210Call a callable object with positional arguments taken from the tuple args,\n\
211and keyword arguments taken from the optional dictionary kwargs.\n\
Raymond Hettingerff41c482003-04-06 09:01:11 +0000212Note that classes are callable, as are instances with a __call__() method.\n\
213\n\
214Deprecated since release 2.3. Instead, use the extended call syntax:\n\
215 function(*args, **keywords).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000216
217
Guido van Rossum79f25d91997-04-29 20:08:16 +0000218static PyObject *
Eric Smith3cd81942008-02-22 16:30:22 +0000219builtin_bin(PyObject *self, PyObject *v)
220{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000221 return PyNumber_ToBase(v, 2);
Eric Smith3cd81942008-02-22 16:30:22 +0000222}
223
224PyDoc_STRVAR(bin_doc,
225"bin(number) -> string\n\
226\n\
227Return the binary representation of an integer or long integer.");
228
229
230static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000231builtin_callable(PyObject *self, PyObject *v)
Guido van Rossum2d951851994-08-29 12:52:16 +0000232{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000233 return PyBool_FromLong((long)PyCallable_Check(v));
Guido van Rossum2d951851994-08-29 12:52:16 +0000234}
235
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000236PyDoc_STRVAR(callable_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000237"callable(object) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000238\n\
239Return whether the object is callable (i.e., some kind of function).\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000240Note that classes are callable, as are instances with a __call__() method.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000241
242
Guido van Rossum79f25d91997-04-29 20:08:16 +0000243static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000244builtin_filter(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000245{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000246 PyObject *func, *seq, *result, *it, *arg;
247 Py_ssize_t len; /* guess for result list size */
248 register Py_ssize_t j;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000249
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000250 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
251 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000252
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000253 /* Strings and tuples return a result of the same type. */
254 if (PyString_Check(seq))
255 return filterstring(func, seq);
Martin v. Löwis8afd7572003-01-25 22:46:11 +0000256#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000257 if (PyUnicode_Check(seq))
258 return filterunicode(func, seq);
Martin v. Löwis8afd7572003-01-25 22:46:11 +0000259#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000260 if (PyTuple_Check(seq))
261 return filtertuple(func, seq);
Tim Peters0e57abf2001-05-02 07:39:38 +0000262
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000263 /* Pre-allocate argument list tuple. */
264 arg = PyTuple_New(1);
265 if (arg == NULL)
266 return NULL;
Georg Brandle35b6572005-07-19 22:20:20 +0000267
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000268 /* Get iterator. */
269 it = PyObject_GetIter(seq);
270 if (it == NULL)
271 goto Fail_arg;
Tim Peters0e57abf2001-05-02 07:39:38 +0000272
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000273 /* Guess a result list size. */
274 len = _PyObject_LengthHint(seq, 8);
275 if (len == -1)
276 goto Fail_it;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000277
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000278 /* Get a result list. */
279 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
280 /* Eww - can modify the list in-place. */
281 Py_INCREF(seq);
282 result = seq;
283 }
284 else {
285 result = PyList_New(len);
286 if (result == NULL)
287 goto Fail_it;
288 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000289
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000290 /* Build the result list. */
291 j = 0;
292 for (;;) {
293 PyObject *item;
294 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000295
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000296 item = PyIter_Next(it);
297 if (item == NULL) {
298 if (PyErr_Occurred())
299 goto Fail_result_it;
300 break;
301 }
Guido van Rossumdc4b93d1993-10-27 14:56:44 +0000302
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000303 if (func == (PyObject *)&PyBool_Type || func == Py_None) {
304 ok = PyObject_IsTrue(item);
305 }
306 else {
307 PyObject *good;
308 PyTuple_SET_ITEM(arg, 0, item);
309 good = PyObject_Call(func, arg, NULL);
310 PyTuple_SET_ITEM(arg, 0, NULL);
311 if (good == NULL) {
312 Py_DECREF(item);
313 goto Fail_result_it;
314 }
315 ok = PyObject_IsTrue(good);
316 Py_DECREF(good);
317 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +0200318 if (ok > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000319 if (j < len)
320 PyList_SET_ITEM(result, j, item);
321 else {
322 int status = PyList_Append(result, item);
323 Py_DECREF(item);
324 if (status < 0)
325 goto Fail_result_it;
326 }
327 ++j;
328 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +0200329 else {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000330 Py_DECREF(item);
Antoine Pitrouc5bef752012-08-15 23:16:51 +0200331 if (ok < 0)
332 goto Fail_result_it;
333 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000334 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000335
Guido van Rossum12d12c51993-10-26 17:58:25 +0000336
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000337 /* Cut back result list if len is too big. */
338 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
339 goto Fail_result_it;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000340
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000341 Py_DECREF(it);
342 Py_DECREF(arg);
343 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000344
Tim Peters0e57abf2001-05-02 07:39:38 +0000345Fail_result_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000346 Py_DECREF(result);
Tim Peters0e57abf2001-05-02 07:39:38 +0000347Fail_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000348 Py_DECREF(it);
Guido van Rossumc7903a12002-08-16 07:04:56 +0000349Fail_arg:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000350 Py_DECREF(arg);
351 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000352}
353
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000354PyDoc_STRVAR(filter_doc,
Tim Petersd50e5442002-03-09 00:06:26 +0000355"filter(function or None, sequence) -> list, tuple, or string\n"
356"\n"
357"Return those items of sequence for which function(item) is true. If\n"
358"function is None, return the items that are true. If sequence is a tuple\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000359"or string, return the same type, else return a list.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000360
Guido van Rossum79f25d91997-04-29 20:08:16 +0000361static PyObject *
Eric Smitha9f7d622008-02-17 19:46:49 +0000362builtin_format(PyObject *self, PyObject *args)
363{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000364 PyObject *value;
365 PyObject *format_spec = NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +0000366
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000367 if (!PyArg_ParseTuple(args, "O|O:format", &value, &format_spec))
368 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +0000369
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000370 return PyObject_Format(value, format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +0000371}
372
373PyDoc_STRVAR(format_doc,
374"format(value[, format_spec]) -> string\n\
375\n\
376Returns value.__format__(format_spec)\n\
377format_spec defaults to \"\"");
378
379static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000380builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000381{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000382 long x;
383 char s[1];
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000384
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000385 if (!PyArg_ParseTuple(args, "l:chr", &x))
386 return NULL;
387 if (x < 0 || x >= 256) {
388 PyErr_SetString(PyExc_ValueError,
389 "chr() arg not in range(256)");
390 return NULL;
391 }
392 s[0] = (char)x;
393 return PyString_FromStringAndSize(s, 1);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000394}
395
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000396PyDoc_STRVAR(chr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000397"chr(i) -> character\n\
398\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000399Return a string of one character with ordinal i; 0 <= i < 256.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000400
401
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000402#ifdef Py_USING_UNICODE
Guido van Rossum79f25d91997-04-29 20:08:16 +0000403static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000404builtin_unichr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000405{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000406 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000407
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000408 if (!PyArg_ParseTuple(args, "i:unichr", &x))
409 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000410
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000411 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000412}
413
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000414PyDoc_STRVAR(unichr_doc,
Fred Drake078b24f2000-04-13 02:42:50 +0000415"unichr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000416\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000417Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000418#endif
Guido van Rossum09095f32000-03-10 23:00:52 +0000419
420
421static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000422builtin_cmp(PyObject *self, PyObject *args)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000423{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000424 PyObject *a, *b;
425 int c;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000426
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000427 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
428 return NULL;
429 if (PyObject_Cmp(a, b, &c) < 0)
430 return NULL;
431 return PyInt_FromLong((long)c);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000432}
433
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000434PyDoc_STRVAR(cmp_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000435"cmp(x, y) -> integer\n\
436\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000437Return negative if x<y, zero if x==y, positive if x>y.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000438
439
Guido van Rossum79f25d91997-04-29 20:08:16 +0000440static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000441builtin_coerce(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000442{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000443 PyObject *v, *w;
444 PyObject *res;
Guido van Rossum5524a591995-01-10 15:26:20 +0000445
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000446 if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
447 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +0000448
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000449 if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
450 return NULL;
451 if (PyNumber_Coerce(&v, &w) < 0)
452 return NULL;
453 res = PyTuple_Pack(2, v, w);
454 Py_DECREF(v);
455 Py_DECREF(w);
456 return res;
Guido van Rossum04691fc1992-08-12 15:35:34 +0000457}
458
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000459PyDoc_STRVAR(coerce_doc,
Martin v. Löwis8d494f32004-08-25 10:42:41 +0000460"coerce(x, y) -> (x1, y1)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000461\n\
Martin v. Löwis8d494f32004-08-25 10:42:41 +0000462Return a tuple consisting of the two numeric arguments converted to\n\
463a common type, using the same rules as used by arithmetic operations.\n\
464If coercion is not possible, raise TypeError.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000465
Guido van Rossum79f25d91997-04-29 20:08:16 +0000466static PyObject *
Georg Brandl5240d742007-03-13 20:46:32 +0000467builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000468{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000469 char *str;
470 char *filename;
471 char *startstr;
472 int mode = -1;
473 int dont_inherit = 0;
474 int supplied_flags = 0;
475 int is_ast;
476 PyCompilerFlags cf;
477 PyObject *result = NULL, *cmd, *tmp = NULL;
478 Py_ssize_t length;
479 static char *kwlist[] = {"source", "filename", "mode", "flags",
480 "dont_inherit", NULL};
481 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000482
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000483 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
484 kwlist, &cmd, &filename, &startstr,
485 &supplied_flags, &dont_inherit))
486 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000487
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000488 cf.cf_flags = supplied_flags;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000489
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000490 if (supplied_flags &
491 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
492 {
493 PyErr_SetString(PyExc_ValueError,
494 "compile(): unrecognised flags");
495 return NULL;
496 }
497 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Georg Brandlfc8eef32008-03-28 12:11:56 +0000498
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000499 if (!dont_inherit) {
500 PyEval_MergeCompilerFlags(&cf);
501 }
Georg Brandlfc8eef32008-03-28 12:11:56 +0000502
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000503 if (strcmp(startstr, "exec") == 0)
504 mode = 0;
505 else if (strcmp(startstr, "eval") == 0)
506 mode = 1;
507 else if (strcmp(startstr, "single") == 0)
508 mode = 2;
509 else {
510 PyErr_SetString(PyExc_ValueError,
511 "compile() arg 3 must be 'exec', 'eval' or 'single'");
512 return NULL;
513 }
Georg Brandlf2bfd542008-03-29 13:24:23 +0000514
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000515 is_ast = PyAST_Check(cmd);
516 if (is_ast == -1)
517 return NULL;
518 if (is_ast) {
519 if (supplied_flags & PyCF_ONLY_AST) {
520 Py_INCREF(cmd);
521 result = cmd;
522 }
523 else {
524 PyArena *arena;
525 mod_ty mod;
Georg Brandlfc8eef32008-03-28 12:11:56 +0000526
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000527 arena = PyArena_New();
Stefan Kraha8857af2012-08-20 17:31:22 +0200528 if (arena == NULL)
529 return NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000530 mod = PyAST_obj2mod(cmd, arena, mode);
531 if (mod == NULL) {
532 PyArena_Free(arena);
533 return NULL;
534 }
535 result = (PyObject*)PyAST_Compile(mod, filename,
536 &cf, arena);
537 PyArena_Free(arena);
538 }
539 return result;
540 }
Serhiy Storchaka61565602015-11-20 21:56:21 +0200541 if (PyString_Check(cmd)) {
542 str = PyString_AS_STRING(cmd);
543 length = PyString_GET_SIZE(cmd);
544 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000545#ifdef Py_USING_UNICODE
Serhiy Storchaka61565602015-11-20 21:56:21 +0200546 else if (PyUnicode_Check(cmd)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000547 tmp = PyUnicode_AsUTF8String(cmd);
548 if (tmp == NULL)
549 return NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000550 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
Serhiy Storchaka61565602015-11-20 21:56:21 +0200551 str = PyString_AS_STRING(tmp);
552 length = PyString_GET_SIZE(tmp);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000553 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000554#endif
Serhiy Storchaka61565602015-11-20 21:56:21 +0200555 else if (!PyObject_AsReadBuffer(cmd, (const void **)&str, &length)) {
556 /* Copy to NUL-terminated buffer. */
557 tmp = PyString_FromStringAndSize(str, length);
558 if (tmp == NULL)
559 return NULL;
560 str = PyString_AS_STRING(tmp);
561 length = PyString_GET_SIZE(tmp);
562 }
563 else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000564 goto cleanup;
565 if ((size_t)length != strlen(str)) {
566 PyErr_SetString(PyExc_TypeError,
567 "compile() expected string without null bytes");
568 goto cleanup;
569 }
570 result = Py_CompileStringFlags(str, filename, start[mode], &cf);
Neal Norwitz3a9a3e72005-11-27 20:38:31 +0000571cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000572 Py_XDECREF(tmp);
573 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000574}
575
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000576PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000577"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000578\n\
579Compile the source string (a Python module, statement or expression)\n\
580into a code object that can be executed by the exec statement or eval().\n\
581The filename will be used for run-time error messages.\n\
582The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000583single (interactive) statement, or 'eval' to compile an expression.\n\
584The flags argument, if present, controls which future statements influence\n\
585the compilation of the code.\n\
586The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
587the effects of any future statements in effect in the code calling\n\
588compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000589in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000590
Guido van Rossum79f25d91997-04-29 20:08:16 +0000591static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000592builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000593{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000594 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000595
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000596 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
597 return NULL;
598 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000599}
600
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000601PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000602"dir([object]) -> list of strings\n"
603"\n"
Georg Brandl871f1bc2007-03-12 13:17:36 +0000604"If called without an argument, return the names in the current scope.\n"
605"Else, return an alphabetized list of names comprising (some of) the attributes\n"
606"of the given object, and of attributes reachable from it.\n"
607"If the object supplies a method named __dir__, it will be used; otherwise\n"
608"the default dir() logic is used and returns:\n"
609" for a module object: the module's attributes.\n"
610" for a class object: its attributes, and recursively the attributes\n"
611" of its bases.\n"
Georg Brandl3bb15672007-03-13 07:23:16 +0000612" for any other object: its attributes, its class's attributes, and\n"
Georg Brandl871f1bc2007-03-12 13:17:36 +0000613" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000614
Guido van Rossum79f25d91997-04-29 20:08:16 +0000615static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000616builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000617{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000618 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000619
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000620 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
621 return NULL;
622 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000623}
624
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000625PyDoc_STRVAR(divmod_doc,
Raymond Hettinger39540a02011-07-19 11:59:20 -0700626"divmod(x, y) -> (quotient, remainder)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000627\n\
Zachary Warefd583492016-04-28 14:38:48 -0500628Return the tuple (x//y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000629
630
Guido van Rossum79f25d91997-04-29 20:08:16 +0000631static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000632builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000633{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000634 PyObject *cmd, *result, *tmp = NULL;
635 PyObject *globals = Py_None, *locals = Py_None;
636 char *str;
637 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000638
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000639 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
640 return NULL;
641 if (locals != Py_None && !PyMapping_Check(locals)) {
642 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
643 return NULL;
644 }
645 if (globals != Py_None && !PyDict_Check(globals)) {
646 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
647 "globals must be a real dict; try eval(expr, {}, mapping)"
648 : "globals must be a dict");
649 return NULL;
650 }
651 if (globals == Py_None) {
652 globals = PyEval_GetGlobals();
653 if (locals == Py_None)
654 locals = PyEval_GetLocals();
655 }
656 else if (locals == Py_None)
657 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000658
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000659 if (globals == NULL || locals == NULL) {
660 PyErr_SetString(PyExc_TypeError,
661 "eval must be given globals and locals "
662 "when called without a frame");
663 return NULL;
664 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000665
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000666 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
667 if (PyDict_SetItemString(globals, "__builtins__",
668 PyEval_GetBuiltins()) != 0)
669 return NULL;
670 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000671
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000672 if (PyCode_Check(cmd)) {
673 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
674 PyErr_SetString(PyExc_TypeError,
675 "code object passed to eval() may not contain free variables");
676 return NULL;
677 }
678 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
679 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000680
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000681 if (!PyString_Check(cmd) &&
682 !PyUnicode_Check(cmd)) {
683 PyErr_SetString(PyExc_TypeError,
684 "eval() arg 1 must be a string or code object");
685 return NULL;
686 }
687 cf.cf_flags = 0;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000688
689#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000690 if (PyUnicode_Check(cmd)) {
691 tmp = PyUnicode_AsUTF8String(cmd);
692 if (tmp == NULL)
693 return NULL;
694 cmd = tmp;
695 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
696 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000697#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000698 if (PyString_AsStringAndSize(cmd, &str, NULL)) {
699 Py_XDECREF(tmp);
700 return NULL;
701 }
702 while (*str == ' ' || *str == '\t')
703 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000704
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000705 (void)PyEval_MergeCompilerFlags(&cf);
706 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
707 Py_XDECREF(tmp);
708 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000709}
710
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000711PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000712"eval(source[, globals[, locals]]) -> value\n\
713\n\
714Evaluate the source in the context of globals and locals.\n\
715The source may be a string representing a Python expression\n\
716or a code object as returned by compile().\n\
Neal Norwitz477ca1c2006-09-05 02:25:41 +0000717The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000718defaulting to the current globals and locals.\n\
719If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000720
721
Guido van Rossum79f25d91997-04-29 20:08:16 +0000722static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000723builtin_execfile(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000724{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000725 char *filename;
726 PyObject *globals = Py_None, *locals = Py_None;
727 PyObject *res;
728 FILE* fp = NULL;
729 PyCompilerFlags cf;
730 int exists;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000731
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000732 if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
733 1) < 0)
734 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +0000735
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000736 if (!PyArg_ParseTuple(args, "s|O!O:execfile",
737 &filename,
738 &PyDict_Type, &globals,
739 &locals))
740 return NULL;
741 if (locals != Py_None && !PyMapping_Check(locals)) {
742 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
743 return NULL;
744 }
745 if (globals == Py_None) {
746 globals = PyEval_GetGlobals();
747 if (locals == Py_None)
748 locals = PyEval_GetLocals();
749 }
750 else if (locals == Py_None)
751 locals = globals;
752 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
753 if (PyDict_SetItemString(globals, "__builtins__",
754 PyEval_GetBuiltins()) != 0)
755 return NULL;
756 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000757
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000758 exists = 0;
759 /* Test for existence or directory. */
Martin v. Löwis3484a182002-03-09 12:07:51 +0000760#if defined(PLAN9)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000761 {
762 Dir *d;
Martin v. Löwis3484a182002-03-09 12:07:51 +0000763
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000764 if ((d = dirstat(filename))!=nil) {
765 if(d->mode & DMDIR)
766 werrstr("is a directory");
767 else
768 exists = 1;
769 free(d);
770 }
771 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000772#elif defined(RISCOS)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000773 if (object_exists(filename)) {
774 if (isdir(filename))
775 errno = EISDIR;
776 else
777 exists = 1;
778 }
779#else /* standard Posix */
780 {
781 struct stat s;
782 if (stat(filename, &s) == 0) {
783 if (S_ISDIR(s.st_mode))
784# if defined(PYOS_OS2) && defined(PYCC_VACPP)
785 errno = EOS2ERR;
786# else
787 errno = EISDIR;
788# endif
789 else
790 exists = 1;
791 }
792 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000793#endif
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000794
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000795 if (exists) {
796 Py_BEGIN_ALLOW_THREADS
797 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
798 Py_END_ALLOW_THREADS
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000799
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000800 if (fp == NULL) {
801 exists = 0;
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000802 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000803 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000804
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000805 if (!exists) {
806 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
807 return NULL;
808 }
809 cf.cf_flags = 0;
810 if (PyEval_MergeCompilerFlags(&cf))
811 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
812 locals, 1, &cf);
813 else
814 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
815 locals, 1);
816 return res;
Guido van Rossum0f61f8a1992-02-25 18:55:05 +0000817}
818
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000819PyDoc_STRVAR(execfile_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000820"execfile(filename[, globals[, locals]])\n\
821\n\
822Read and execute a Python script from a file.\n\
823The globals and locals are dictionaries, defaulting to the current\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000824globals and locals. If only globals is given, locals defaults to it.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000825
826
Guido van Rossum79f25d91997-04-29 20:08:16 +0000827static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000828builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000829{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000830 PyObject *v, *result, *dflt = NULL;
831 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000832
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000833 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
834 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000835#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000836 if (PyUnicode_Check(name)) {
837 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
838 if (name == NULL)
839 return NULL;
840 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000841#endif
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000842
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000843 if (!PyString_Check(name)) {
844 PyErr_SetString(PyExc_TypeError,
845 "getattr(): attribute name must be string");
846 return NULL;
847 }
848 result = PyObject_GetAttr(v, name);
849 if (result == NULL && dflt != NULL &&
850 PyErr_ExceptionMatches(PyExc_AttributeError))
851 {
852 PyErr_Clear();
853 Py_INCREF(dflt);
854 result = dflt;
855 }
856 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000857}
858
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000859PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000860"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000861\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000862Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
863When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000864exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000865
866
Guido van Rossum79f25d91997-04-29 20:08:16 +0000867static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000868builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000869{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000870 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000871
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000872 d = PyEval_GetGlobals();
873 Py_XINCREF(d);
874 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000875}
876
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000877PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000878"globals() -> dictionary\n\
879\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000880Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000881
882
Guido van Rossum79f25d91997-04-29 20:08:16 +0000883static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000884builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000885{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000886 PyObject *v;
887 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000888
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000889 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
890 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000891#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000892 if (PyUnicode_Check(name)) {
893 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
894 if (name == NULL)
895 return NULL;
896 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000897#endif
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000898
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000899 if (!PyString_Check(name)) {
900 PyErr_SetString(PyExc_TypeError,
901 "hasattr(): attribute name must be string");
902 return NULL;
903 }
904 v = PyObject_GetAttr(v, name);
905 if (v == NULL) {
906 if (!PyErr_ExceptionMatches(PyExc_Exception))
907 return NULL;
908 else {
909 PyErr_Clear();
910 Py_INCREF(Py_False);
911 return Py_False;
912 }
913 }
914 Py_DECREF(v);
915 Py_INCREF(Py_True);
916 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000917}
918
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000919PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000920"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000921\n\
922Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000923(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000924
925
Guido van Rossum79f25d91997-04-29 20:08:16 +0000926static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000927builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000928{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000929 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000930}
931
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000932PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000933"id(object) -> integer\n\
934\n\
935Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000936simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000937
938
Guido van Rossum79f25d91997-04-29 20:08:16 +0000939static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000940builtin_map(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000941{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000942 typedef struct {
943 PyObject *it; /* the iterator object */
944 int saw_StopIteration; /* bool: did the iterator end? */
945 } sequence;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000946
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000947 PyObject *func, *result;
948 sequence *seqs = NULL, *sqp;
949 Py_ssize_t n, len;
950 register int i, j;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000951
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000952 n = PyTuple_Size(args);
953 if (n < 2) {
954 PyErr_SetString(PyExc_TypeError,
955 "map() requires at least two args");
956 return NULL;
957 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000958
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000959 func = PyTuple_GetItem(args, 0);
960 n--;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000961
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000962 if (func == Py_None) {
963 if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
964 "use list(...)", 1) < 0)
965 return NULL;
966 if (n == 1) {
967 /* map(None, S) is the same as list(S). */
968 return PySequence_List(PyTuple_GetItem(args, 1));
969 }
970 }
Guido van Rossumfa4ac711998-07-10 17:37:30 +0000971
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000972 /* Get space for sequence descriptors. Must NULL out the iterator
973 * pointers so that jumping to Fail_2 later doesn't see trash.
974 */
975 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
976 PyErr_NoMemory();
977 return NULL;
978 }
979 for (i = 0; i < n; ++i) {
980 seqs[i].it = (PyObject*)NULL;
981 seqs[i].saw_StopIteration = 0;
982 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000983
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000984 /* Do a first pass to obtain iterators for the arguments, and set len
985 * to the largest of their lengths.
986 */
987 len = 0;
988 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
989 PyObject *curseq;
990 Py_ssize_t curlen;
Guido van Rossumad991772001-01-12 16:03:05 +0000991
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000992 /* Get iterator. */
993 curseq = PyTuple_GetItem(args, i+1);
994 sqp->it = PyObject_GetIter(curseq);
995 if (sqp->it == NULL) {
996 static char errmsg[] =
997 "argument %d to map() must support iteration";
998 char errbuf[sizeof(errmsg) + 25];
999 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
1000 PyErr_SetString(PyExc_TypeError, errbuf);
1001 goto Fail_2;
1002 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001003
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001004 /* Update len. */
1005 curlen = _PyObject_LengthHint(curseq, 8);
1006 if (curlen > len)
1007 len = curlen;
1008 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001009
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001010 /* Get space for the result list. */
1011 if ((result = (PyObject *) PyList_New(len)) == NULL)
1012 goto Fail_2;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001013
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001014 /* Iterate over the sequences until all have stopped. */
1015 for (i = 0; ; ++i) {
1016 PyObject *alist, *item=NULL, *value;
1017 int numactive = 0;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001018
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001019 if (func == Py_None && n == 1)
1020 alist = NULL;
1021 else if ((alist = PyTuple_New(n)) == NULL)
1022 goto Fail_1;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001023
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001024 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
1025 if (sqp->saw_StopIteration) {
1026 Py_INCREF(Py_None);
1027 item = Py_None;
1028 }
1029 else {
1030 item = PyIter_Next(sqp->it);
1031 if (item)
1032 ++numactive;
1033 else {
1034 if (PyErr_Occurred()) {
1035 Py_XDECREF(alist);
1036 goto Fail_1;
1037 }
1038 Py_INCREF(Py_None);
1039 item = Py_None;
1040 sqp->saw_StopIteration = 1;
1041 }
1042 }
1043 if (alist)
1044 PyTuple_SET_ITEM(alist, j, item);
1045 else
1046 break;
1047 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001048
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001049 if (!alist)
1050 alist = item;
Guido van Rossum2d951851994-08-29 12:52:16 +00001051
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001052 if (numactive == 0) {
1053 Py_DECREF(alist);
1054 break;
1055 }
Guido van Rossum2d951851994-08-29 12:52:16 +00001056
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001057 if (func == Py_None)
1058 value = alist;
1059 else {
1060 value = PyEval_CallObject(func, alist);
1061 Py_DECREF(alist);
1062 if (value == NULL)
1063 goto Fail_1;
1064 }
1065 if (i >= len) {
1066 int status = PyList_Append(result, value);
1067 Py_DECREF(value);
1068 if (status < 0)
1069 goto Fail_1;
1070 }
1071 else if (PyList_SetItem(result, i, value) < 0)
1072 goto Fail_1;
1073 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001074
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001075 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
1076 goto Fail_1;
Guido van Rossumfa4ac711998-07-10 17:37:30 +00001077
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001078 goto Succeed;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001079
Guido van Rossum12d12c51993-10-26 17:58:25 +00001080Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001081 Py_DECREF(result);
Guido van Rossum12d12c51993-10-26 17:58:25 +00001082Fail_2:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001083 result = NULL;
Tim Peters4e9afdc2001-05-03 23:54:49 +00001084Succeed:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001085 assert(seqs);
1086 for (i = 0; i < n; ++i)
1087 Py_XDECREF(seqs[i].it);
1088 PyMem_DEL(seqs);
1089 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001090}
1091
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001092PyDoc_STRVAR(map_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001093"map(function, sequence[, sequence, ...]) -> list\n\
1094\n\
1095Return a list of the results of applying the function to the items of\n\
1096the argument sequence(s). If more than one sequence is given, the\n\
1097function is called with an argument list consisting of the corresponding\n\
1098item of each sequence, substituting None for missing values when not all\n\
1099sequences have the same length. If the function is None, return a list of\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001100the items of the sequence (or a list of tuples if more than one sequence).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001101
1102
Guido van Rossum79f25d91997-04-29 20:08:16 +00001103static PyObject *
Georg Brandl28e08732008-04-30 19:47:09 +00001104builtin_next(PyObject *self, PyObject *args)
1105{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001106 PyObject *it, *res;
1107 PyObject *def = NULL;
Georg Brandl28e08732008-04-30 19:47:09 +00001108
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001109 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1110 return NULL;
1111 if (!PyIter_Check(it)) {
1112 PyErr_Format(PyExc_TypeError,
1113 "%.200s object is not an iterator",
1114 it->ob_type->tp_name);
1115 return NULL;
1116 }
1117
1118 res = (*it->ob_type->tp_iternext)(it);
1119 if (res != NULL) {
1120 return res;
1121 } else if (def != NULL) {
1122 if (PyErr_Occurred()) {
1123 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
1124 return NULL;
1125 PyErr_Clear();
1126 }
1127 Py_INCREF(def);
1128 return def;
1129 } else if (PyErr_Occurred()) {
1130 return NULL;
1131 } else {
1132 PyErr_SetNone(PyExc_StopIteration);
1133 return NULL;
1134 }
Georg Brandl28e08732008-04-30 19:47:09 +00001135}
1136
1137PyDoc_STRVAR(next_doc,
1138"next(iterator[, default])\n\
1139\n\
1140Return the next item from the iterator. If default is given and the iterator\n\
1141is exhausted, it is returned instead of raising StopIteration.");
1142
1143
1144static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001145builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001146{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001147 PyObject *v;
1148 PyObject *name;
1149 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001150
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001151 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1152 return NULL;
1153 if (PyObject_SetAttr(v, name, value) != 0)
1154 return NULL;
1155 Py_INCREF(Py_None);
1156 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001157}
1158
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001159PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001160"setattr(object, name, value)\n\
1161\n\
1162Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001163``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001164
1165
Guido van Rossum79f25d91997-04-29 20:08:16 +00001166static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001167builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001168{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001169 PyObject *v;
1170 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001171
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001172 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1173 return NULL;
1174 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1175 return NULL;
1176 Py_INCREF(Py_None);
1177 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001178}
1179
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001180PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001181"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001182\n\
1183Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001184``del x.y''.");
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_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001189{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001190 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001191
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001192 x = PyObject_Hash(v);
1193 if (x == -1)
1194 return NULL;
1195 return PyInt_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001196}
1197
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001198PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001199"hash(object) -> integer\n\
1200\n\
1201Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001202the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001203
1204
Guido van Rossum79f25d91997-04-29 20:08:16 +00001205static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001206builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001207{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001208 PyNumberMethods *nb;
1209 PyObject *res;
Benjamin Petersonc6d64ec2008-05-17 20:09:42 +00001210
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001211 if ((nb = v->ob_type->tp_as_number) == NULL ||
1212 nb->nb_hex == NULL) {
1213 PyErr_SetString(PyExc_TypeError,
1214 "hex() argument can't be converted to hex");
1215 return NULL;
1216 }
1217 res = (*nb->nb_hex)(v);
1218 if (res && !PyString_Check(res)) {
1219 PyErr_Format(PyExc_TypeError,
1220 "__hex__ returned non-string (type %.200s)",
1221 res->ob_type->tp_name);
1222 Py_DECREF(res);
1223 return NULL;
1224 }
1225 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001226}
1227
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001228PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001229"hex(number) -> string\n\
1230\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001231Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001232
1233
Tim Petersdbd9ba62000-07-09 03:09:57 +00001234static PyObject *builtin_raw_input(PyObject *, PyObject *);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001235
Guido van Rossum79f25d91997-04-29 20:08:16 +00001236static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001237builtin_input(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001238{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001239 PyObject *line;
1240 char *str;
1241 PyObject *res;
1242 PyObject *globals, *locals;
1243 PyCompilerFlags cf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001244
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001245 line = builtin_raw_input(self, args);
1246 if (line == NULL)
1247 return line;
1248 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1249 return NULL;
1250 while (*str == ' ' || *str == '\t')
1251 str++;
1252 globals = PyEval_GetGlobals();
1253 locals = PyEval_GetLocals();
1254 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1255 if (PyDict_SetItemString(globals, "__builtins__",
1256 PyEval_GetBuiltins()) != 0)
1257 return NULL;
1258 }
1259 cf.cf_flags = 0;
1260 PyEval_MergeCompilerFlags(&cf);
1261 res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1262 Py_DECREF(line);
1263 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001264}
1265
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001266PyDoc_STRVAR(input_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001267"input([prompt]) -> value\n\
1268\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001269Equivalent to eval(raw_input(prompt)).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001270
1271
Guido van Rossume8811f81997-02-14 15:48:05 +00001272static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001273builtin_intern(PyObject *self, PyObject *args)
Guido van Rossume8811f81997-02-14 15:48:05 +00001274{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001275 PyObject *s;
1276 if (!PyArg_ParseTuple(args, "S:intern", &s))
1277 return NULL;
1278 if (!PyString_CheckExact(s)) {
1279 PyErr_SetString(PyExc_TypeError,
1280 "can't intern subclass of string");
1281 return NULL;
1282 }
1283 Py_INCREF(s);
1284 PyString_InternInPlace(&s);
1285 return s;
Guido van Rossume8811f81997-02-14 15:48:05 +00001286}
1287
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001288PyDoc_STRVAR(intern_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001289"intern(string) -> string\n\
1290\n\
1291``Intern'' the given string. This enters the string in the (global)\n\
1292table of interned strings whose purpose is to speed up dictionary lookups.\n\
1293Return the string itself or the previously interned string object with the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001294same value.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001295
1296
Guido van Rossum79f25d91997-04-29 20:08:16 +00001297static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001298builtin_iter(PyObject *self, PyObject *args)
1299{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001300 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001301
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001302 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1303 return NULL;
1304 if (w == NULL)
1305 return PyObject_GetIter(v);
1306 if (!PyCallable_Check(v)) {
1307 PyErr_SetString(PyExc_TypeError,
1308 "iter(v, w): v must be callable");
1309 return NULL;
1310 }
1311 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001312}
1313
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001314PyDoc_STRVAR(iter_doc,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001315"iter(collection) -> iterator\n\
1316iter(callable, sentinel) -> iterator\n\
1317\n\
1318Get an iterator from an object. In the first form, the argument must\n\
1319supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001320In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001321
1322
1323static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001324builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001325{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001326 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001327
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001328 res = PyObject_Size(v);
1329 if (res < 0 && PyErr_Occurred())
1330 return NULL;
1331 return PyInt_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001332}
1333
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001334PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001335"len(object) -> integer\n\
1336\n\
Terry Jan Reedy9f2dcd22014-06-16 03:05:30 -04001337Return the number of items of a sequence or collection.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001338
1339
Guido van Rossum79f25d91997-04-29 20:08:16 +00001340static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001341builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001342{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001343 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001344
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001345 d = PyEval_GetLocals();
1346 Py_XINCREF(d);
1347 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001348}
1349
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001350PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001351"locals() -> dictionary\n\
1352\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001353Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001354
1355
Guido van Rossum79f25d91997-04-29 20:08:16 +00001356static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001357min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001358{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001359 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1360 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001361
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001362 if (PyTuple_Size(args) > 1)
1363 v = args;
1364 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1365 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001366
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001367 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1368 keyfunc = PyDict_GetItemString(kwds, "key");
1369 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1370 PyErr_Format(PyExc_TypeError,
1371 "%s() got an unexpected keyword argument", name);
1372 return NULL;
1373 }
1374 Py_INCREF(keyfunc);
1375 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001376
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001377 it = PyObject_GetIter(v);
1378 if (it == NULL) {
1379 Py_XDECREF(keyfunc);
1380 return NULL;
1381 }
Tim Petersc3074532001-05-03 07:00:32 +00001382
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001383 maxitem = NULL; /* the result */
1384 maxval = NULL; /* the value associated with the result */
1385 while (( item = PyIter_Next(it) )) {
1386 /* get the value from the key function */
1387 if (keyfunc != NULL) {
1388 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1389 if (val == NULL)
1390 goto Fail_it_item;
1391 }
1392 /* no key function; the value is the item */
1393 else {
1394 val = item;
1395 Py_INCREF(val);
1396 }
Tim Petersc3074532001-05-03 07:00:32 +00001397
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001398 /* maximum value and item are unset; set them */
1399 if (maxval == NULL) {
1400 maxitem = item;
1401 maxval = val;
1402 }
1403 /* maximum value and item are set; update them as necessary */
1404 else {
1405 int cmp = PyObject_RichCompareBool(val, maxval, op);
1406 if (cmp < 0)
1407 goto Fail_it_item_and_val;
1408 else if (cmp > 0) {
1409 Py_DECREF(maxval);
1410 Py_DECREF(maxitem);
1411 maxval = val;
1412 maxitem = item;
1413 }
1414 else {
1415 Py_DECREF(item);
1416 Py_DECREF(val);
1417 }
1418 }
1419 }
1420 if (PyErr_Occurred())
1421 goto Fail_it;
1422 if (maxval == NULL) {
1423 PyErr_Format(PyExc_ValueError,
1424 "%s() arg is an empty sequence", name);
1425 assert(maxitem == NULL);
1426 }
1427 else
1428 Py_DECREF(maxval);
1429 Py_DECREF(it);
1430 Py_XDECREF(keyfunc);
1431 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001432
1433Fail_it_item_and_val:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001434 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001435Fail_it_item:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001436 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001437Fail_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001438 Py_XDECREF(maxval);
1439 Py_XDECREF(maxitem);
1440 Py_DECREF(it);
1441 Py_XDECREF(keyfunc);
1442 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001443}
1444
Guido van Rossum79f25d91997-04-29 20:08:16 +00001445static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001446builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001447{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001448 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001449}
1450
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001451PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001452"min(iterable[, key=func]) -> value\n\
1453min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001454\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001455With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001456With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001457
1458
Guido van Rossum79f25d91997-04-29 20:08:16 +00001459static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001460builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001461{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001462 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001463}
1464
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001465PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001466"max(iterable[, key=func]) -> value\n\
1467max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001468\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001469With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001470With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001471
1472
Guido van Rossum79f25d91997-04-29 20:08:16 +00001473static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001474builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001475{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001476 PyNumberMethods *nb;
1477 PyObject *res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001478
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001479 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1480 nb->nb_oct == NULL) {
1481 PyErr_SetString(PyExc_TypeError,
1482 "oct() argument can't be converted to oct");
1483 return NULL;
1484 }
1485 res = (*nb->nb_oct)(v);
1486 if (res && !PyString_Check(res)) {
1487 PyErr_Format(PyExc_TypeError,
1488 "__oct__ returned non-string (type %.200s)",
1489 res->ob_type->tp_name);
1490 Py_DECREF(res);
1491 return NULL;
1492 }
1493 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001494}
1495
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001496PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001497"oct(number) -> string\n\
1498\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001499Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001500
1501
Guido van Rossum79f25d91997-04-29 20:08:16 +00001502static PyObject *
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001503builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
1504{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001505 return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001506}
1507
1508PyDoc_STRVAR(open_doc,
1509"open(name[, mode[, buffering]]) -> file object\n\
1510\n\
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00001511Open a file using the file() type, returns a file object. This is the\n\
Philip Jenveydd0388a2009-05-28 03:12:16 +00001512preferred way to open a file. See file.__doc__ for further information.");
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001513
1514
1515static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001516builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001517{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001518 long ord;
1519 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001520
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001521 if (PyString_Check(obj)) {
1522 size = PyString_GET_SIZE(obj);
1523 if (size == 1) {
1524 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1525 return PyInt_FromLong(ord);
1526 }
1527 } else if (PyByteArray_Check(obj)) {
1528 size = PyByteArray_GET_SIZE(obj);
1529 if (size == 1) {
1530 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1531 return PyInt_FromLong(ord);
1532 }
Christian Heimes1a6387e2008-03-26 12:49:49 +00001533
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001534#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001535 } else if (PyUnicode_Check(obj)) {
1536 size = PyUnicode_GET_SIZE(obj);
1537 if (size == 1) {
1538 ord = (long)*PyUnicode_AS_UNICODE(obj);
1539 return PyInt_FromLong(ord);
1540 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001541#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001542 } else {
1543 PyErr_Format(PyExc_TypeError,
1544 "ord() expected string of length 1, but " \
1545 "%.200s found", obj->ob_type->tp_name);
1546 return NULL;
1547 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001548
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001549 PyErr_Format(PyExc_TypeError,
1550 "ord() expected a character, "
1551 "but string of length %zd found",
1552 size);
1553 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001554}
1555
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001556PyDoc_STRVAR(ord_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001557"ord(c) -> integer\n\
1558\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001559Return the integer ordinal of a one-character string.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001560
1561
Guido van Rossum79f25d91997-04-29 20:08:16 +00001562static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001563builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001564{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001565 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001566
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001567 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1568 return NULL;
1569 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001570}
1571
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001572PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001573"pow(x, y[, z]) -> number\n\
1574\n\
1575With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001576equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001577
1578
Eric Smith7c478942008-03-18 23:45:49 +00001579static PyObject *
1580builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1581{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001582 static char *kwlist[] = {"sep", "end", "file", 0};
1583 static PyObject *dummy_args = NULL;
1584 static PyObject *unicode_newline = NULL, *unicode_space = NULL;
1585 static PyObject *str_newline = NULL, *str_space = NULL;
1586 PyObject *newline, *space;
1587 PyObject *sep = NULL, *end = NULL, *file = NULL;
1588 int i, err, use_unicode = 0;
Eric Smith7c478942008-03-18 23:45:49 +00001589
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001590 if (dummy_args == NULL) {
1591 if (!(dummy_args = PyTuple_New(0)))
1592 return NULL;
1593 }
1594 if (str_newline == NULL) {
1595 str_newline = PyString_FromString("\n");
1596 if (str_newline == NULL)
1597 return NULL;
1598 str_space = PyString_FromString(" ");
1599 if (str_space == NULL) {
1600 Py_CLEAR(str_newline);
1601 return NULL;
1602 }
Martin v. Löwised11a5d2012-05-20 10:42:17 +02001603#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001604 unicode_newline = PyUnicode_FromString("\n");
1605 if (unicode_newline == NULL) {
1606 Py_CLEAR(str_newline);
1607 Py_CLEAR(str_space);
1608 return NULL;
1609 }
1610 unicode_space = PyUnicode_FromString(" ");
1611 if (unicode_space == NULL) {
1612 Py_CLEAR(str_newline);
1613 Py_CLEAR(str_space);
1614 Py_CLEAR(unicode_space);
1615 return NULL;
1616 }
Martin v. Löwised11a5d2012-05-20 10:42:17 +02001617#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001618 }
1619 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1620 kwlist, &sep, &end, &file))
1621 return NULL;
1622 if (file == NULL || file == Py_None) {
1623 file = PySys_GetObject("stdout");
1624 /* sys.stdout may be None when FILE* stdout isn't connected */
1625 if (file == Py_None)
1626 Py_RETURN_NONE;
1627 }
1628 if (sep == Py_None) {
1629 sep = NULL;
1630 }
1631 else if (sep) {
1632 if (PyUnicode_Check(sep)) {
1633 use_unicode = 1;
1634 }
1635 else if (!PyString_Check(sep)) {
1636 PyErr_Format(PyExc_TypeError,
1637 "sep must be None, str or unicode, not %.200s",
1638 sep->ob_type->tp_name);
1639 return NULL;
1640 }
1641 }
1642 if (end == Py_None)
1643 end = NULL;
1644 else if (end) {
1645 if (PyUnicode_Check(end)) {
1646 use_unicode = 1;
1647 }
1648 else if (!PyString_Check(end)) {
1649 PyErr_Format(PyExc_TypeError,
1650 "end must be None, str or unicode, not %.200s",
1651 end->ob_type->tp_name);
1652 return NULL;
1653 }
1654 }
Benjamin Peterson753d1622009-07-02 18:16:45 +00001655
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001656 if (!use_unicode) {
1657 for (i = 0; i < PyTuple_Size(args); i++) {
1658 if (PyUnicode_Check(PyTuple_GET_ITEM(args, i))) {
1659 use_unicode = 1;
1660 break;
1661 }
1662 }
1663 }
1664 if (use_unicode) {
1665 newline = unicode_newline;
1666 space = unicode_space;
1667 }
1668 else {
1669 newline = str_newline;
1670 space = str_space;
1671 }
Eric Smith7c478942008-03-18 23:45:49 +00001672
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001673 for (i = 0; i < PyTuple_Size(args); i++) {
1674 if (i > 0) {
1675 if (sep == NULL)
1676 err = PyFile_WriteObject(space, file,
1677 Py_PRINT_RAW);
1678 else
1679 err = PyFile_WriteObject(sep, file,
1680 Py_PRINT_RAW);
1681 if (err)
1682 return NULL;
1683 }
1684 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1685 Py_PRINT_RAW);
1686 if (err)
1687 return NULL;
1688 }
Eric Smith7c478942008-03-18 23:45:49 +00001689
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001690 if (end == NULL)
1691 err = PyFile_WriteObject(newline, file, Py_PRINT_RAW);
1692 else
1693 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1694 if (err)
1695 return NULL;
Eric Smith7c478942008-03-18 23:45:49 +00001696
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001697 Py_RETURN_NONE;
Eric Smith7c478942008-03-18 23:45:49 +00001698}
1699
1700PyDoc_STRVAR(print_doc,
1701"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
1702\n\
1703Prints the values to a stream, or to sys.stdout by default.\n\
1704Optional keyword arguments:\n\
1705file: a file-like object (stream); defaults to the current sys.stdout.\n\
1706sep: string inserted between values, default a space.\n\
1707end: string appended after the last value, default a newline.");
1708
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001709
1710/* Return number of items in range (lo, hi, step), when arguments are
1711 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1712 * & only if the true value is too large to fit in a signed long.
1713 * Arguments MUST return 1 with either PyInt_Check() or
1714 * PyLong_Check(). Return -1 when there is an error.
1715 */
1716static long
1717get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
1718{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001719 /* -------------------------------------------------------------
1720 Algorithm is equal to that of get_len_of_range(), but it operates
1721 on PyObjects (which are assumed to be PyLong or PyInt objects).
1722 ---------------------------------------------------------------*/
1723 long n;
1724 PyObject *diff = NULL;
1725 PyObject *one = NULL;
1726 PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
1727 /* holds sub-expression evaluations */
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001728
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001729 /* if (lo >= hi), return length of 0. */
1730 if (PyObject_Compare(lo, hi) >= 0)
1731 return 0;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001732
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001733 if ((one = PyLong_FromLong(1L)) == NULL)
1734 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001735
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001736 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
1737 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001738
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001739 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
1740 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001741
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001742 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
1743 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001744
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001745 if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
1746 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001747
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001748 n = PyLong_AsLong(tmp3);
1749 if (PyErr_Occurred()) { /* Check for Overflow */
1750 PyErr_Clear();
1751 goto Fail;
1752 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001753
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001754 Py_DECREF(tmp3);
1755 Py_DECREF(tmp2);
1756 Py_DECREF(diff);
1757 Py_DECREF(tmp1);
1758 Py_DECREF(one);
1759 return n;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001760
1761 Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001762 Py_XDECREF(tmp3);
1763 Py_XDECREF(tmp2);
1764 Py_XDECREF(diff);
1765 Py_XDECREF(tmp1);
1766 Py_XDECREF(one);
1767 return -1;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001768}
1769
Mark Dickinsona8d26682010-05-04 16:18:25 +00001770/* Helper function for handle_range_longs. If arg is int or long
1771 object, returns it with incremented reference count. If arg is
1772 float, raises type error. As a last resort, creates a new int by
1773 calling arg type's nb_int method if it is defined. Returns NULL
1774 and sets exception on error.
1775
1776 Returns a new reference to an int object. */
1777static PyObject *
1778get_range_long_argument(PyObject *arg, const char *name)
1779{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001780 PyObject *v;
1781 PyNumberMethods *nb;
1782 if (PyInt_Check(arg) || PyLong_Check(arg)) {
1783 Py_INCREF(arg);
1784 return arg;
1785 }
1786 if (PyFloat_Check(arg) ||
1787 (nb = Py_TYPE(arg)->tp_as_number) == NULL ||
1788 nb->nb_int == NULL) {
1789 PyErr_Format(PyExc_TypeError,
1790 "range() integer %s argument expected, got %s.",
1791 name, arg->ob_type->tp_name);
1792 return NULL;
1793 }
1794 v = nb->nb_int(arg);
1795 if (v == NULL)
1796 return NULL;
1797 if (PyInt_Check(v) || PyLong_Check(v))
1798 return v;
1799 Py_DECREF(v);
1800 PyErr_SetString(PyExc_TypeError,
1801 "__int__ should return int object");
1802 return NULL;
Mark Dickinsona8d26682010-05-04 16:18:25 +00001803}
1804
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001805/* An extension of builtin_range() that handles the case when PyLong
1806 * arguments are given. */
1807static PyObject *
Mark Dickinsonef9b4ab2010-05-04 16:19:06 +00001808handle_range_longs(PyObject *self, PyObject *args)
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001809{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001810 PyObject *ilow = NULL;
1811 PyObject *ihigh = NULL;
1812 PyObject *istep = NULL;
Tim Peters874e1f72003-04-13 22:13:08 +00001813
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001814 PyObject *low = NULL;
1815 PyObject *high = NULL;
1816 PyObject *step = NULL;
Mark Dickinsona8d26682010-05-04 16:18:25 +00001817
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001818 PyObject *curnum = NULL;
1819 PyObject *v = NULL;
1820 long bign;
1821 Py_ssize_t i, n;
1822 int cmp_result;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001823
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001824 PyObject *zero = PyLong_FromLong(0);
Tim Peters874e1f72003-04-13 22:13:08 +00001825
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001826 if (zero == NULL)
1827 return NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001828
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001829 if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
1830 Py_DECREF(zero);
1831 return NULL;
1832 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001833
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001834 /* Figure out which way we were called, supply defaults, and be
1835 * sure to incref everything so that the decrefs at the end
1836 * are correct. NB: ilow, ihigh and istep are borrowed references.
1837 */
1838 assert(ilow != NULL);
1839 if (ihigh == NULL) {
1840 /* only 1 arg -- it's the upper limit */
1841 ihigh = ilow;
1842 ilow = NULL;
1843 }
Mark Dickinsona8d26682010-05-04 16:18:25 +00001844
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001845 /* convert ihigh if necessary */
1846 assert(ihigh != NULL);
1847 high = get_range_long_argument(ihigh, "end");
1848 if (high == NULL)
1849 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001850
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001851 /* ihigh correct now; do ilow */
1852 if (ilow == NULL) {
1853 Py_INCREF(zero);
1854 low = zero;
1855 }
1856 else {
1857 low = get_range_long_argument(ilow, "start");
1858 if (low == NULL)
1859 goto Fail;
1860 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001861
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001862 /* ilow and ihigh correct now; do istep */
1863 if (istep == NULL)
1864 step = PyLong_FromLong(1);
1865 else
1866 step = get_range_long_argument(istep, "step");
1867 if (step == NULL)
1868 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001869
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001870 if (PyObject_Cmp(step, zero, &cmp_result) == -1)
1871 goto Fail;
Tim Peters874e1f72003-04-13 22:13:08 +00001872
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001873 if (cmp_result == 0) {
1874 PyErr_SetString(PyExc_ValueError,
1875 "range() step argument must not be zero");
1876 goto Fail;
1877 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001878
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001879 if (cmp_result > 0)
1880 bign = get_len_of_range_longs(low, high, step);
1881 else {
1882 PyObject *neg_step = PyNumber_Negative(step);
1883 if (neg_step == NULL)
1884 goto Fail;
1885 bign = get_len_of_range_longs(high, low, neg_step);
1886 Py_DECREF(neg_step);
1887 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001888
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001889 n = (Py_ssize_t)bign;
1890 if (bign < 0 || (long)n != bign) {
1891 PyErr_SetString(PyExc_OverflowError,
1892 "range() result has too many items");
1893 goto Fail;
1894 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001895
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001896 v = PyList_New(n);
1897 if (v == NULL)
1898 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001899
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001900 curnum = low;
1901 Py_INCREF(curnum);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001902
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001903 for (i = 0; i < n; i++) {
1904 PyObject *w = PyNumber_Long(curnum);
1905 PyObject *tmp_num;
1906 if (w == NULL)
1907 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001908
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001909 PyList_SET_ITEM(v, i, w);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001910
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001911 tmp_num = PyNumber_Add(curnum, step);
1912 if (tmp_num == NULL)
1913 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001914
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001915 Py_DECREF(curnum);
1916 curnum = tmp_num;
1917 }
1918 Py_DECREF(low);
1919 Py_DECREF(high);
1920 Py_DECREF(step);
1921 Py_DECREF(zero);
1922 Py_DECREF(curnum);
1923 return v;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001924
1925 Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001926 Py_XDECREF(low);
1927 Py_XDECREF(high);
1928 Py_XDECREF(step);
1929 Py_DECREF(zero);
1930 Py_XDECREF(curnum);
1931 Py_XDECREF(v);
1932 return NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001933}
1934
Guido van Rossum124eff01999-02-23 16:11:01 +00001935/* Return number of items in range/xrange (lo, hi, step). step > 0
1936 * required. Return a value < 0 if & only if the true value is too
1937 * large to fit in a signed long.
1938 */
1939static long
Thomas Wouterse28c2962000-07-23 22:21:32 +00001940get_len_of_range(long lo, long hi, long step)
Guido van Rossum124eff01999-02-23 16:11:01 +00001941{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001942 /* -------------------------------------------------------------
1943 If lo >= hi, the range is empty.
1944 Else if n values are in the range, the last one is
1945 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1946 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1947 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1948 the RHS is non-negative and so truncation is the same as the
1949 floor. Letting M be the largest positive long, the worst case
1950 for the RHS numerator is hi=M, lo=-M-1, and then
1951 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1952 precision to compute the RHS exactly.
1953 ---------------------------------------------------------------*/
1954 long n = 0;
1955 if (lo < hi) {
1956 unsigned long uhi = (unsigned long)hi;
1957 unsigned long ulo = (unsigned long)lo;
1958 unsigned long diff = uhi - ulo - 1;
1959 n = (long)(diff / (unsigned long)step + 1);
1960 }
1961 return n;
Guido van Rossum124eff01999-02-23 16:11:01 +00001962}
1963
Guido van Rossum79f25d91997-04-29 20:08:16 +00001964static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001965builtin_range(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001966{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001967 long ilow = 0, ihigh = 0, istep = 1;
1968 long bign;
1969 Py_ssize_t i, n;
Guido van Rossum124eff01999-02-23 16:11:01 +00001970
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001971 PyObject *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001972
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001973 if (PyTuple_Size(args) <= 1) {
1974 if (!PyArg_ParseTuple(args,
1975 "l;range() requires 1-3 int arguments",
1976 &ihigh)) {
1977 PyErr_Clear();
1978 return handle_range_longs(self, args);
1979 }
1980 }
1981 else {
1982 if (!PyArg_ParseTuple(args,
1983 "ll|l;range() requires 1-3 int arguments",
1984 &ilow, &ihigh, &istep)) {
1985 PyErr_Clear();
1986 return handle_range_longs(self, args);
1987 }
1988 }
1989 if (istep == 0) {
1990 PyErr_SetString(PyExc_ValueError,
1991 "range() step argument must not be zero");
1992 return NULL;
1993 }
1994 if (istep > 0)
1995 bign = get_len_of_range(ilow, ihigh, istep);
1996 else
1997 bign = get_len_of_range(ihigh, ilow, -istep);
1998 n = (Py_ssize_t)bign;
1999 if (bign < 0 || (long)n != bign) {
2000 PyErr_SetString(PyExc_OverflowError,
2001 "range() result has too many items");
2002 return NULL;
2003 }
2004 v = PyList_New(n);
2005 if (v == NULL)
2006 return NULL;
2007 for (i = 0; i < n; i++) {
2008 PyObject *w = PyInt_FromLong(ilow);
2009 if (w == NULL) {
2010 Py_DECREF(v);
2011 return NULL;
2012 }
2013 PyList_SET_ITEM(v, i, w);
2014 ilow += istep;
2015 }
2016 return v;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002017}
2018
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002019PyDoc_STRVAR(range_doc,
Chris Jerdonekad4b0002012-10-07 20:37:54 -07002020"range(stop) -> list of integers\n\
2021range(start, stop[, step]) -> list of integers\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002022\n\
2023Return a list containing an arithmetic progression of integers.\n\
2024range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
2025When step is given, it specifies the increment (or decrement).\n\
2026For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002027These are exactly the valid indices for a list of 4 elements.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002028
2029
Guido van Rossum79f25d91997-04-29 20:08:16 +00002030static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002031builtin_raw_input(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002032{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002033 PyObject *v = NULL;
2034 PyObject *fin = PySys_GetObject("stdin");
2035 PyObject *fout = PySys_GetObject("stdout");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002036
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002037 if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
2038 return NULL;
Martin v. Löwis31d2df52002-08-14 15:46:02 +00002039
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002040 if (fin == NULL) {
2041 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
2042 return NULL;
2043 }
2044 if (fout == NULL) {
2045 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
2046 return NULL;
2047 }
2048 if (PyFile_SoftSpace(fout, 0)) {
2049 if (PyFile_WriteString(" ", fout) != 0)
2050 return NULL;
2051 }
2052 if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
2053 && isatty(fileno(PyFile_AsFile(fin)))
2054 && isatty(fileno(PyFile_AsFile(fout)))) {
2055 PyObject *po;
2056 char *prompt;
2057 char *s;
2058 PyObject *result;
2059 if (v != NULL) {
2060 po = PyObject_Str(v);
2061 if (po == NULL)
2062 return NULL;
2063 prompt = PyString_AsString(po);
2064 if (prompt == NULL)
2065 return NULL;
2066 }
2067 else {
2068 po = NULL;
2069 prompt = "";
2070 }
2071 s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
2072 prompt);
2073 Py_XDECREF(po);
2074 if (s == NULL) {
2075 if (!PyErr_Occurred())
2076 PyErr_SetNone(PyExc_KeyboardInterrupt);
2077 return NULL;
2078 }
2079 if (*s == '\0') {
2080 PyErr_SetNone(PyExc_EOFError);
2081 result = NULL;
2082 }
2083 else { /* strip trailing '\n' */
2084 size_t len = strlen(s);
2085 if (len > PY_SSIZE_T_MAX) {
2086 PyErr_SetString(PyExc_OverflowError,
2087 "[raw_]input: input too long");
2088 result = NULL;
2089 }
2090 else {
2091 result = PyString_FromStringAndSize(s, len-1);
2092 }
2093 }
2094 PyMem_FREE(s);
2095 return result;
2096 }
2097 if (v != NULL) {
2098 if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
2099 return NULL;
2100 }
2101 return PyFile_GetLine(fin, -1);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002102}
2103
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002104PyDoc_STRVAR(raw_input_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002105"raw_input([prompt]) -> string\n\
2106\n\
2107Read a string from standard input. The trailing newline is stripped.\n\
2108If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
2109On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002110is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002111
2112
Guido van Rossum79f25d91997-04-29 20:08:16 +00002113static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002114builtin_reduce(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002115{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002116 static PyObject *functools_reduce = NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002117
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002118 if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
2119 "use functools.reduce()", 1) < 0)
2120 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +00002121
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002122 if (functools_reduce == NULL) {
2123 PyObject *functools = PyImport_ImportModule("functools");
2124 if (functools == NULL)
2125 return NULL;
2126 functools_reduce = PyObject_GetAttrString(functools, "reduce");
2127 Py_DECREF(functools);
2128 if (functools_reduce == NULL)
2129 return NULL;
2130 }
2131 return PyObject_Call(functools_reduce, args, NULL);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002132}
2133
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002134PyDoc_STRVAR(reduce_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002135"reduce(function, sequence[, initial]) -> value\n\
2136\n\
2137Apply a function of two arguments cumulatively to the items of a sequence,\n\
2138from left to right, so as to reduce the sequence to a single value.\n\
2139For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
2140((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
2141of the sequence in the calculation, and serves as a default when the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002142sequence is empty.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002143
2144
Guido van Rossum79f25d91997-04-29 20:08:16 +00002145static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002146builtin_reload(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002147{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002148 if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
2149 1) < 0)
2150 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +00002151
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002152 return PyImport_ReloadModule(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002153}
2154
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002155PyDoc_STRVAR(reload_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002156"reload(module) -> module\n\
2157\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002158Reload the module. The module must have been successfully imported before.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002159
2160
Guido van Rossum79f25d91997-04-29 20:08:16 +00002161static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002162builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00002163{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002164 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002165}
2166
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002167PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002168"repr(object) -> string\n\
2169\n\
2170Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002171For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002172
2173
Guido van Rossum79f25d91997-04-29 20:08:16 +00002174static PyObject *
Georg Brandlccadf842006-03-31 18:54:53 +00002175builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002176{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002177 double x;
2178 PyObject *o_ndigits = NULL;
2179 Py_ssize_t ndigits;
2180 static char *kwlist[] = {"number", "ndigits", 0};
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002181
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002182 if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|O:round",
2183 kwlist, &x, &o_ndigits))
2184 return NULL;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002185
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002186 if (o_ndigits == NULL) {
2187 /* second argument defaults to 0 */
2188 ndigits = 0;
2189 }
2190 else {
2191 /* interpret 2nd argument as a Py_ssize_t; clip on overflow */
2192 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
2193 if (ndigits == -1 && PyErr_Occurred())
2194 return NULL;
2195 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002196
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002197 /* nans, infinities and zeros round to themselves */
2198 if (!Py_IS_FINITE(x) || x == 0.0)
2199 return PyFloat_FromDouble(x);
Mark Dickinsonbce78372009-11-24 10:54:58 +00002200
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002201 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
2202 always rounds to itself. For ndigits < NDIGITS_MIN, x always
2203 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002204#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
2205#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002206 if (ndigits > NDIGITS_MAX)
2207 /* return x */
2208 return PyFloat_FromDouble(x);
2209 else if (ndigits < NDIGITS_MIN)
2210 /* return 0.0, but with sign of x */
2211 return PyFloat_FromDouble(0.0*x);
2212 else
2213 /* finite x, and ndigits is not unreasonably large */
2214 /* _Py_double_round is defined in floatobject.c */
2215 return _Py_double_round(x, (int)ndigits);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002216#undef NDIGITS_MAX
2217#undef NDIGITS_MIN
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002218}
2219
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002220PyDoc_STRVAR(round_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002221"round(number[, ndigits]) -> floating point number\n\
2222\n\
2223Round a number to a given precision in decimal digits (default 0 digits).\n\
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +00002224This always returns a floating point number. Precision may be negative.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002225
Raymond Hettinger64958a12003-12-17 20:43:33 +00002226static PyObject *
2227builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2228{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002229 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
2230 PyObject *callable;
2231 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
2232 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002233
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002234 /* args 1-4 should match listsort in Objects/listobject.c */
2235 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
2236 kwlist, &seq, &compare, &keyfunc, &reverse))
2237 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002238
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002239 newlist = PySequence_List(seq);
2240 if (newlist == NULL)
2241 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002242
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002243 callable = PyObject_GetAttrString(newlist, "sort");
2244 if (callable == NULL) {
2245 Py_DECREF(newlist);
2246 return NULL;
2247 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002248
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002249 newargs = PyTuple_GetSlice(args, 1, 4);
2250 if (newargs == NULL) {
2251 Py_DECREF(newlist);
2252 Py_DECREF(callable);
2253 return NULL;
2254 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00002255
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002256 v = PyObject_Call(callable, newargs, kwds);
2257 Py_DECREF(newargs);
2258 Py_DECREF(callable);
2259 if (v == NULL) {
2260 Py_DECREF(newlist);
2261 return NULL;
2262 }
2263 Py_DECREF(v);
2264 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002265}
2266
2267PyDoc_STRVAR(sorted_doc,
2268"sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002269
Guido van Rossum79f25d91997-04-29 20:08:16 +00002270static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002271builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002272{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002273 PyObject *v = NULL;
2274 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002275
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002276 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2277 return NULL;
2278 if (v == NULL) {
2279 d = PyEval_GetLocals();
2280 if (d == NULL) {
2281 if (!PyErr_Occurred())
2282 PyErr_SetString(PyExc_SystemError,
2283 "vars(): no locals!?");
2284 }
2285 else
2286 Py_INCREF(d);
2287 }
2288 else {
2289 d = PyObject_GetAttrString(v, "__dict__");
2290 if (d == NULL) {
2291 PyErr_SetString(PyExc_TypeError,
2292 "vars() argument must have __dict__ attribute");
2293 return NULL;
2294 }
2295 }
2296 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002297}
2298
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002299PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002300"vars([object]) -> dictionary\n\
2301\n\
2302Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002303With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002304
Alex Martellia70b1912003-04-22 08:12:33 +00002305
2306static PyObject*
2307builtin_sum(PyObject *self, PyObject *args)
2308{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002309 PyObject *seq;
2310 PyObject *result = NULL;
2311 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002312
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002313 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
2314 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002315
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002316 iter = PyObject_GetIter(seq);
2317 if (iter == NULL)
2318 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002319
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002320 if (result == NULL) {
2321 result = PyInt_FromLong(0);
2322 if (result == NULL) {
2323 Py_DECREF(iter);
2324 return NULL;
2325 }
2326 } else {
2327 /* reject string values for 'start' parameter */
2328 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
2329 PyErr_SetString(PyExc_TypeError,
2330 "sum() can't sum strings [use ''.join(seq) instead]");
2331 Py_DECREF(iter);
2332 return NULL;
2333 }
2334 Py_INCREF(result);
2335 }
Alex Martellia70b1912003-04-22 08:12:33 +00002336
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002337#ifndef SLOW_SUM
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002338 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2339 Assumes all inputs are the same type. If the assumption fails, default
2340 to the more general routine.
2341 */
2342 if (PyInt_CheckExact(result)) {
2343 long i_result = PyInt_AS_LONG(result);
2344 Py_DECREF(result);
2345 result = NULL;
2346 while(result == NULL) {
2347 item = PyIter_Next(iter);
2348 if (item == NULL) {
2349 Py_DECREF(iter);
2350 if (PyErr_Occurred())
2351 return NULL;
2352 return PyInt_FromLong(i_result);
2353 }
2354 if (PyInt_CheckExact(item)) {
2355 long b = PyInt_AS_LONG(item);
2356 long x = i_result + b;
2357 if ((x^i_result) >= 0 || (x^b) >= 0) {
2358 i_result = x;
2359 Py_DECREF(item);
2360 continue;
2361 }
2362 }
2363 /* Either overflowed or is not an int. Restore real objects and process normally */
2364 result = PyInt_FromLong(i_result);
2365 temp = PyNumber_Add(result, item);
2366 Py_DECREF(result);
2367 Py_DECREF(item);
2368 result = temp;
2369 if (result == NULL) {
2370 Py_DECREF(iter);
2371 return NULL;
2372 }
2373 }
2374 }
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002375
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002376 if (PyFloat_CheckExact(result)) {
2377 double f_result = PyFloat_AS_DOUBLE(result);
2378 Py_DECREF(result);
2379 result = NULL;
2380 while(result == NULL) {
2381 item = PyIter_Next(iter);
2382 if (item == NULL) {
2383 Py_DECREF(iter);
2384 if (PyErr_Occurred())
2385 return NULL;
2386 return PyFloat_FromDouble(f_result);
2387 }
2388 if (PyFloat_CheckExact(item)) {
2389 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2390 f_result += PyFloat_AS_DOUBLE(item);
2391 PyFPE_END_PROTECT(f_result)
2392 Py_DECREF(item);
2393 continue;
2394 }
2395 if (PyInt_CheckExact(item)) {
2396 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2397 f_result += (double)PyInt_AS_LONG(item);
2398 PyFPE_END_PROTECT(f_result)
2399 Py_DECREF(item);
2400 continue;
2401 }
2402 result = PyFloat_FromDouble(f_result);
2403 temp = PyNumber_Add(result, item);
2404 Py_DECREF(result);
2405 Py_DECREF(item);
2406 result = temp;
2407 if (result == NULL) {
2408 Py_DECREF(iter);
2409 return NULL;
2410 }
2411 }
2412 }
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002413#endif
2414
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002415 for(;;) {
2416 item = PyIter_Next(iter);
2417 if (item == NULL) {
2418 /* error, or end-of-sequence */
2419 if (PyErr_Occurred()) {
2420 Py_DECREF(result);
2421 result = NULL;
2422 }
2423 break;
2424 }
2425 /* It's tempting to use PyNumber_InPlaceAdd instead of
2426 PyNumber_Add here, to avoid quadratic running time
2427 when doing 'sum(list_of_lists, [])'. However, this
2428 would produce a change in behaviour: a snippet like
Mark Dickinson0e0e2152009-10-26 14:18:44 +00002429
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002430 empty = []
2431 sum([[x] for x in range(10)], empty)
Mark Dickinson0e0e2152009-10-26 14:18:44 +00002432
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002433 would change the value of empty. */
2434 temp = PyNumber_Add(result, item);
2435 Py_DECREF(result);
2436 Py_DECREF(item);
2437 result = temp;
2438 if (result == NULL)
2439 break;
2440 }
2441 Py_DECREF(iter);
2442 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002443}
2444
2445PyDoc_STRVAR(sum_doc,
Georg Brandl8134d062006-10-12 12:33:07 +00002446"sum(sequence[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002447\n\
R David Murrayf7c85842013-07-10 16:23:15 -04002448Return the sum of a sequence of numbers (NOT strings) plus the value\n\
Georg Brandl8134d062006-10-12 12:33:07 +00002449of parameter 'start' (which defaults to 0). When the sequence is\n\
R David Murrayf7c85842013-07-10 16:23:15 -04002450empty, return start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002451
2452
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002453static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002454builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002455{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002456 PyObject *inst;
2457 PyObject *cls;
2458 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002459
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002460 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2461 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002462
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002463 retval = PyObject_IsInstance(inst, cls);
2464 if (retval < 0)
2465 return NULL;
2466 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002467}
2468
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002469PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002470"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002471\n\
2472Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002473With a type as second argument, return whether that is the object's type.\n\
2474The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002475isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002476
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002477
2478static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002479builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002480{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002481 PyObject *derived;
2482 PyObject *cls;
2483 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002484
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002485 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2486 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002487
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002488 retval = PyObject_IsSubclass(derived, cls);
2489 if (retval < 0)
2490 return NULL;
2491 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002492}
2493
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002494PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002495"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002496\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002497Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2498When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2499is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002500
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002501
Barry Warsawbd599b52000-08-03 15:45:29 +00002502static PyObject*
2503builtin_zip(PyObject *self, PyObject *args)
2504{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002505 PyObject *ret;
2506 const Py_ssize_t itemsize = PySequence_Length(args);
2507 Py_ssize_t i;
2508 PyObject *itlist; /* tuple of iterators */
2509 Py_ssize_t len; /* guess at result length */
Barry Warsawbd599b52000-08-03 15:45:29 +00002510
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002511 if (itemsize == 0)
2512 return PyList_New(0);
Raymond Hettingereaef6152003-08-02 07:42:57 +00002513
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002514 /* args must be a tuple */
2515 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002516
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002517 /* Guess at result length: the shortest of the input lengths.
2518 If some argument refuses to say, we refuse to guess too, lest
2519 an argument like xrange(sys.maxint) lead us astray.*/
2520 len = -1; /* unknown */
2521 for (i = 0; i < itemsize; ++i) {
2522 PyObject *item = PyTuple_GET_ITEM(args, i);
2523 Py_ssize_t thislen = _PyObject_LengthHint(item, -2);
2524 if (thislen < 0) {
2525 if (thislen == -1)
2526 return NULL;
2527 len = -1;
2528 break;
2529 }
2530 else if (len < 0 || thislen < len)
2531 len = thislen;
2532 }
Tim Peters67d687a2002-04-29 21:27:32 +00002533
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002534 /* allocate result list */
2535 if (len < 0)
2536 len = 10; /* arbitrary */
2537 if ((ret = PyList_New(len)) == NULL)
2538 return NULL;
Barry Warsawbd599b52000-08-03 15:45:29 +00002539
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002540 /* obtain iterators */
2541 itlist = PyTuple_New(itemsize);
2542 if (itlist == NULL)
2543 goto Fail_ret;
2544 for (i = 0; i < itemsize; ++i) {
2545 PyObject *item = PyTuple_GET_ITEM(args, i);
2546 PyObject *it = PyObject_GetIter(item);
2547 if (it == NULL) {
2548 if (PyErr_ExceptionMatches(PyExc_TypeError))
2549 PyErr_Format(PyExc_TypeError,
2550 "zip argument #%zd must support iteration",
2551 i+1);
2552 goto Fail_ret_itlist;
2553 }
2554 PyTuple_SET_ITEM(itlist, i, it);
2555 }
Barry Warsawbd599b52000-08-03 15:45:29 +00002556
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002557 /* build result into ret list */
2558 for (i = 0; ; ++i) {
2559 int j;
2560 PyObject *next = PyTuple_New(itemsize);
2561 if (!next)
2562 goto Fail_ret_itlist;
Tim Peters8572b4f2001-05-06 01:05:02 +00002563
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002564 for (j = 0; j < itemsize; j++) {
2565 PyObject *it = PyTuple_GET_ITEM(itlist, j);
2566 PyObject *item = PyIter_Next(it);
2567 if (!item) {
2568 if (PyErr_Occurred()) {
2569 Py_DECREF(ret);
2570 ret = NULL;
2571 }
2572 Py_DECREF(next);
2573 Py_DECREF(itlist);
2574 goto Done;
2575 }
2576 PyTuple_SET_ITEM(next, j, item);
2577 }
Tim Peters8572b4f2001-05-06 01:05:02 +00002578
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002579 if (i < len)
2580 PyList_SET_ITEM(ret, i, next);
2581 else {
2582 int status = PyList_Append(ret, next);
2583 Py_DECREF(next);
2584 ++len;
2585 if (status < 0)
2586 goto Fail_ret_itlist;
2587 }
2588 }
Tim Peters8572b4f2001-05-06 01:05:02 +00002589
Tim Peters67d687a2002-04-29 21:27:32 +00002590Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002591 if (ret != NULL && i < len) {
2592 /* The list is too big. */
2593 if (PyList_SetSlice(ret, i, len, NULL) < 0)
2594 return NULL;
2595 }
2596 return ret;
Tim Peters67d687a2002-04-29 21:27:32 +00002597
Tim Peters8572b4f2001-05-06 01:05:02 +00002598Fail_ret_itlist:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002599 Py_DECREF(itlist);
Tim Peters8572b4f2001-05-06 01:05:02 +00002600Fail_ret:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002601 Py_DECREF(ret);
2602 return NULL;
Barry Warsawbd599b52000-08-03 15:45:29 +00002603}
2604
2605
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002606PyDoc_STRVAR(zip_doc,
Barry Warsawbd599b52000-08-03 15:45:29 +00002607"zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2608\n\
2609Return a list of tuples, where each tuple contains the i-th element\n\
2610from each of the argument sequences. The returned list is truncated\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002611in length to the length of the shortest argument sequence.");
Barry Warsawbd599b52000-08-03 15:45:29 +00002612
2613
Guido van Rossum79f25d91997-04-29 20:08:16 +00002614static PyMethodDef builtin_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002615 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2616 {"abs", builtin_abs, METH_O, abs_doc},
2617 {"all", builtin_all, METH_O, all_doc},
2618 {"any", builtin_any, METH_O, any_doc},
2619 {"apply", builtin_apply, METH_VARARGS, apply_doc},
2620 {"bin", builtin_bin, METH_O, bin_doc},
2621 {"callable", builtin_callable, METH_O, callable_doc},
2622 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2623 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
2624 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
2625 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2626 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2627 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2628 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2629 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2630 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
2631 {"filter", builtin_filter, METH_VARARGS, filter_doc},
2632 {"format", builtin_format, METH_VARARGS, format_doc},
2633 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2634 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2635 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2636 {"hash", builtin_hash, METH_O, hash_doc},
2637 {"hex", builtin_hex, METH_O, hex_doc},
2638 {"id", builtin_id, METH_O, id_doc},
2639 {"input", builtin_input, METH_VARARGS, input_doc},
2640 {"intern", builtin_intern, METH_VARARGS, intern_doc},
2641 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2642 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2643 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2644 {"len", builtin_len, METH_O, len_doc},
2645 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2646 {"map", builtin_map, METH_VARARGS, map_doc},
2647 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2648 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2649 {"next", builtin_next, METH_VARARGS, next_doc},
2650 {"oct", builtin_oct, METH_O, oct_doc},
2651 {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
2652 {"ord", builtin_ord, METH_O, ord_doc},
2653 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2654 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2655 {"range", builtin_range, METH_VARARGS, range_doc},
2656 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
2657 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
2658 {"reload", builtin_reload, METH_O, reload_doc},
2659 {"repr", builtin_repr, METH_O, repr_doc},
2660 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2661 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2662 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2663 {"sum", builtin_sum, METH_VARARGS, sum_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002664#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002665 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002666#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002667 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2668 {"zip", builtin_zip, METH_VARARGS, zip_doc},
2669 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002670};
2671
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002672PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002673"Built-in functions, exceptions, and other objects.\n\
2674\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002675Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002676
Guido van Rossum25ce5661997-08-02 03:10:38 +00002677PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002678_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002679{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002680 PyObject *mod, *dict, *debug;
2681 mod = Py_InitModule4("__builtin__", builtin_methods,
2682 builtin_doc, (PyObject *)NULL,
2683 PYTHON_API_VERSION);
2684 if (mod == NULL)
2685 return NULL;
2686 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002687
Tim Peters7571a0f2003-03-23 17:52:28 +00002688#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002689 /* __builtin__ exposes a number of statically allocated objects
2690 * that, before this code was added in 2.3, never showed up in
2691 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2692 * result, programs leaking references to None and False (etc)
2693 * couldn't be diagnosed by examining sys.getobjects(0).
2694 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002695#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2696#else
2697#define ADD_TO_ALL(OBJECT) (void)0
2698#endif
2699
Tim Peters4b7625e2001-09-13 21:37:17 +00002700#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002701 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2702 return NULL; \
2703 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002704
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002705 SETBUILTIN("None", Py_None);
2706 SETBUILTIN("Ellipsis", Py_Ellipsis);
2707 SETBUILTIN("NotImplemented", Py_NotImplemented);
2708 SETBUILTIN("False", Py_False);
2709 SETBUILTIN("True", Py_True);
2710 SETBUILTIN("basestring", &PyBaseString_Type);
2711 SETBUILTIN("bool", &PyBool_Type);
2712 SETBUILTIN("memoryview", &PyMemoryView_Type);
2713 SETBUILTIN("bytearray", &PyByteArray_Type);
2714 SETBUILTIN("bytes", &PyString_Type);
2715 SETBUILTIN("buffer", &PyBuffer_Type);
2716 SETBUILTIN("classmethod", &PyClassMethod_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002717#ifndef WITHOUT_COMPLEX
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002718 SETBUILTIN("complex", &PyComplex_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002719#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002720 SETBUILTIN("dict", &PyDict_Type);
2721 SETBUILTIN("enumerate", &PyEnum_Type);
2722 SETBUILTIN("file", &PyFile_Type);
2723 SETBUILTIN("float", &PyFloat_Type);
2724 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2725 SETBUILTIN("property", &PyProperty_Type);
2726 SETBUILTIN("int", &PyInt_Type);
2727 SETBUILTIN("list", &PyList_Type);
2728 SETBUILTIN("long", &PyLong_Type);
2729 SETBUILTIN("object", &PyBaseObject_Type);
2730 SETBUILTIN("reversed", &PyReversed_Type);
2731 SETBUILTIN("set", &PySet_Type);
2732 SETBUILTIN("slice", &PySlice_Type);
2733 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2734 SETBUILTIN("str", &PyString_Type);
2735 SETBUILTIN("super", &PySuper_Type);
2736 SETBUILTIN("tuple", &PyTuple_Type);
2737 SETBUILTIN("type", &PyType_Type);
2738 SETBUILTIN("xrange", &PyRange_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002739#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002740 SETBUILTIN("unicode", &PyUnicode_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002741#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002742 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2743 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2744 Py_XDECREF(debug);
2745 return NULL;
2746 }
2747 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002748
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002749 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002750#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002751#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002752}
2753
Guido van Rossume77a7571993-11-03 15:01:26 +00002754/* Helper for filter(): filter a tuple through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002755
Guido van Rossum79f25d91997-04-29 20:08:16 +00002756static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002757filtertuple(PyObject *func, PyObject *tuple)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002758{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002759 PyObject *result;
2760 Py_ssize_t i, j;
2761 Py_ssize_t len = PyTuple_Size(tuple);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002762
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002763 if (len == 0) {
2764 if (PyTuple_CheckExact(tuple))
2765 Py_INCREF(tuple);
2766 else
2767 tuple = PyTuple_New(0);
2768 return tuple;
2769 }
Guido van Rossumb7b45621995-08-04 04:07:45 +00002770
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002771 if ((result = PyTuple_New(len)) == NULL)
2772 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002773
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002774 for (i = j = 0; i < len; ++i) {
2775 PyObject *item, *good;
2776 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002777
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002778 if (tuple->ob_type->tp_as_sequence &&
2779 tuple->ob_type->tp_as_sequence->sq_item) {
2780 item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
2781 if (item == NULL)
2782 goto Fail_1;
2783 } else {
2784 PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
2785 goto Fail_1;
2786 }
2787 if (func == Py_None) {
2788 Py_INCREF(item);
2789 good = item;
2790 }
2791 else {
2792 PyObject *arg = PyTuple_Pack(1, item);
2793 if (arg == NULL) {
2794 Py_DECREF(item);
2795 goto Fail_1;
2796 }
2797 good = PyEval_CallObject(func, arg);
2798 Py_DECREF(arg);
2799 if (good == NULL) {
2800 Py_DECREF(item);
2801 goto Fail_1;
2802 }
2803 }
2804 ok = PyObject_IsTrue(good);
2805 Py_DECREF(good);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002806 if (ok > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002807 if (PyTuple_SetItem(result, j++, item) < 0)
2808 goto Fail_1;
2809 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002810 else {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002811 Py_DECREF(item);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002812 if (ok < 0)
2813 goto Fail_1;
2814 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002815 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002816
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002817 if (_PyTuple_Resize(&result, j) < 0)
2818 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002819
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002820 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002821
Guido van Rossum12d12c51993-10-26 17:58:25 +00002822Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002823 Py_DECREF(result);
2824 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002825}
2826
2827
Guido van Rossume77a7571993-11-03 15:01:26 +00002828/* Helper for filter(): filter a string through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002829
Guido van Rossum79f25d91997-04-29 20:08:16 +00002830static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002831filterstring(PyObject *func, PyObject *strobj)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002832{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002833 PyObject *result;
2834 Py_ssize_t i, j;
2835 Py_ssize_t len = PyString_Size(strobj);
2836 Py_ssize_t outlen = len;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002837
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002838 if (func == Py_None) {
2839 /* If it's a real string we can return the original,
2840 * as no character is ever false and __getitem__
2841 * does return this character. If it's a subclass
2842 * we must go through the __getitem__ loop */
2843 if (PyString_CheckExact(strobj)) {
2844 Py_INCREF(strobj);
2845 return strobj;
2846 }
2847 }
2848 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2849 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002850
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002851 for (i = j = 0; i < len; ++i) {
2852 PyObject *item;
2853 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002854
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002855 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2856 if (item == NULL)
2857 goto Fail_1;
2858 if (func==Py_None) {
2859 ok = 1;
2860 } else {
2861 PyObject *arg, *good;
2862 arg = PyTuple_Pack(1, item);
2863 if (arg == NULL) {
2864 Py_DECREF(item);
2865 goto Fail_1;
2866 }
2867 good = PyEval_CallObject(func, arg);
2868 Py_DECREF(arg);
2869 if (good == NULL) {
2870 Py_DECREF(item);
2871 goto Fail_1;
2872 }
2873 ok = PyObject_IsTrue(good);
2874 Py_DECREF(good);
2875 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002876 if (ok > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002877 Py_ssize_t reslen;
2878 if (!PyString_Check(item)) {
2879 PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
2880 " __getitem__ returned different type");
2881 Py_DECREF(item);
2882 goto Fail_1;
2883 }
2884 reslen = PyString_GET_SIZE(item);
2885 if (reslen == 1) {
2886 PyString_AS_STRING(result)[j++] =
2887 PyString_AS_STRING(item)[0];
2888 } else {
2889 /* do we need more space? */
2890 Py_ssize_t need = j;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002891
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002892 /* calculate space requirements while checking for overflow */
2893 if (need > PY_SSIZE_T_MAX - reslen) {
2894 Py_DECREF(item);
2895 goto Fail_1;
2896 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002897
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002898 need += reslen;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002899
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002900 if (need > PY_SSIZE_T_MAX - len) {
2901 Py_DECREF(item);
2902 goto Fail_1;
2903 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002904
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002905 need += len;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002906
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002907 if (need <= i) {
2908 Py_DECREF(item);
2909 goto Fail_1;
2910 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002911
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002912 need = need - i - 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002913
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002914 assert(need >= 0);
2915 assert(outlen >= 0);
Gregory P. Smith9d534572008-06-11 07:41:16 +00002916
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002917 if (need > outlen) {
2918 /* overallocate, to avoid reallocations */
2919 if (outlen > PY_SSIZE_T_MAX / 2) {
2920 Py_DECREF(item);
2921 return NULL;
2922 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002923
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002924 if (need<2*outlen) {
2925 need = 2*outlen;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002926 }
Martin Panterca56dd42016-09-17 07:54:55 +00002927 if (_PyString_Resize(&result, need)) {
2928 Py_DECREF(item);
2929 return NULL;
2930 }
2931 outlen = need;
2932 }
2933 memcpy(
2934 PyString_AS_STRING(result) + j,
2935 PyString_AS_STRING(item),
2936 reslen
2937 );
2938 j += reslen;
2939 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002940 }
2941 Py_DECREF(item);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002942 if (ok < 0)
2943 goto Fail_1;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002944 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002945
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002946 if (j < outlen)
2947 _PyString_Resize(&result, j);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002948
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002949 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002950
Guido van Rossum12d12c51993-10-26 17:58:25 +00002951Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002952 Py_DECREF(result);
2953 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002954}
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002955
2956#ifdef Py_USING_UNICODE
2957/* Helper for filter(): filter a Unicode object through a function */
2958
2959static PyObject *
2960filterunicode(PyObject *func, PyObject *strobj)
2961{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002962 PyObject *result;
2963 register Py_ssize_t i, j;
2964 Py_ssize_t len = PyUnicode_GetSize(strobj);
2965 Py_ssize_t outlen = len;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002966
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002967 if (func == Py_None) {
2968 /* If it's a real string we can return the original,
2969 * as no character is ever false and __getitem__
2970 * does return this character. If it's a subclass
2971 * we must go through the __getitem__ loop */
2972 if (PyUnicode_CheckExact(strobj)) {
2973 Py_INCREF(strobj);
2974 return strobj;
2975 }
2976 }
2977 if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
2978 return NULL;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002979
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002980 for (i = j = 0; i < len; ++i) {
2981 PyObject *item, *arg, *good;
2982 int ok;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002983
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002984 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2985 if (item == NULL)
2986 goto Fail_1;
2987 if (func == Py_None) {
2988 ok = 1;
2989 } else {
2990 arg = PyTuple_Pack(1, item);
2991 if (arg == NULL) {
2992 Py_DECREF(item);
2993 goto Fail_1;
2994 }
2995 good = PyEval_CallObject(func, arg);
2996 Py_DECREF(arg);
2997 if (good == NULL) {
2998 Py_DECREF(item);
2999 goto Fail_1;
3000 }
3001 ok = PyObject_IsTrue(good);
3002 Py_DECREF(good);
3003 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +02003004 if (ok > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003005 Py_ssize_t reslen;
3006 if (!PyUnicode_Check(item)) {
3007 PyErr_SetString(PyExc_TypeError,
3008 "can't filter unicode to unicode:"
3009 " __getitem__ returned different type");
3010 Py_DECREF(item);
3011 goto Fail_1;
3012 }
3013 reslen = PyUnicode_GET_SIZE(item);
3014 if (reslen == 1)
3015 PyUnicode_AS_UNICODE(result)[j++] =
3016 PyUnicode_AS_UNICODE(item)[0];
3017 else {
3018 /* do we need more space? */
3019 Py_ssize_t need = j + reslen + len - i - 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003020
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003021 /* check that didnt overflow */
3022 if ((j > PY_SSIZE_T_MAX - reslen) ||
3023 ((j + reslen) > PY_SSIZE_T_MAX - len) ||
3024 ((j + reslen + len) < i) ||
3025 ((j + reslen + len - i) <= 0)) {
3026 Py_DECREF(item);
3027 return NULL;
3028 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00003029
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003030 assert(need >= 0);
3031 assert(outlen >= 0);
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003032
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003033 if (need > outlen) {
Martin Panterca56dd42016-09-17 07:54:55 +00003034 /* overallocate, to avoid reallocations */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003035 if (need < 2 * outlen) {
Martin Panterca56dd42016-09-17 07:54:55 +00003036 if (outlen > PY_SSIZE_T_MAX / 2) {
3037 Py_DECREF(item);
3038 return NULL;
3039 } else {
3040 need = 2 * outlen;
3041 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003042 }
Martin Panterca56dd42016-09-17 07:54:55 +00003043
3044 if (PyUnicode_Resize(&result, need) < 0) {
3045 Py_DECREF(item);
3046 goto Fail_1;
3047 }
3048 outlen = need;
3049 }
3050 memcpy(PyUnicode_AS_UNICODE(result) + j,
3051 PyUnicode_AS_UNICODE(item),
3052 reslen*sizeof(Py_UNICODE));
3053 j += reslen;
3054 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003055 }
3056 Py_DECREF(item);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02003057 if (ok < 0)
3058 goto Fail_1;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003059 }
3060
3061 if (j < outlen)
3062 PyUnicode_Resize(&result, j);
3063
3064 return result;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003065
3066Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003067 Py_DECREF(result);
3068 return NULL;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003069}
3070#endif