blob: b4f0e24aaf7bccbf3fc175483e01999928c622d5 [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Georg Brandlfc8eef32008-03-28 12:11:56 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum5b722181993-03-30 17:46:03 +00008#include "eval.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00009
Guido van Rossum6bf62da1997-04-11 20:37:35 +000010#include <ctype.h>
Mark Dickinsonbd15a062009-11-18 19:33:35 +000011#include <float.h> /* for DBL_MANT_DIG and friends */
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012
Guido van Rossume2ae77b2001-10-24 20:42:55 +000013#ifdef RISCOS
14#include "unixstuff.h"
15#endif
16
Mark Hammond26cffde2001-05-14 12:17:34 +000017/* The default encoding used by the platform file system APIs
18 Can remain NULL for all platforms that don't have such a concept
19*/
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000020#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Mark Hammond26cffde2001-05-14 12:17:34 +000021const char *Py_FileSystemDefaultEncoding = "mbcs";
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000022#elif defined(__APPLE__)
23const char *Py_FileSystemDefaultEncoding = "utf-8";
Mark Hammond26cffde2001-05-14 12:17:34 +000024#else
25const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
26#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000027
Guido van Rossum12d12c51993-10-26 17:58:25 +000028/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000029static PyObject *filterstring(PyObject *, PyObject *);
Martin v. Löwis8afd7572003-01-25 22:46:11 +000030#ifdef Py_USING_UNICODE
31static PyObject *filterunicode(PyObject *, PyObject *);
32#endif
Tim Petersdbd9ba62000-07-09 03:09:57 +000033static PyObject *filtertuple (PyObject *, PyObject *);
Guido van Rossum12d12c51993-10-26 17:58:25 +000034
Guido van Rossum79f25d91997-04-29 20:08:16 +000035static PyObject *
Neal Norwitz92e212f2006-04-03 04:48:37 +000036builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +000037{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000038 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
39 "level", 0};
40 char *name;
41 PyObject *globals = NULL;
42 PyObject *locals = NULL;
43 PyObject *fromlist = NULL;
44 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +000045
Antoine Pitrouc83ea132010-05-09 14:46:46 +000046 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
47 kwlist, &name, &globals, &locals, &fromlist, &level))
48 return NULL;
49 return PyImport_ImportModuleLevel(name, globals, locals,
50 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +000051}
52
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000053PyDoc_STRVAR(import_doc,
Neal Norwitz92e212f2006-04-03 04:48:37 +000054"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000055\n\
R David Murray59488d22012-07-18 19:44:08 -040056Import a module. Because this function is meant for use by the Python\n\
57interpreter and not for general use it is better to use\n\
58importlib.import_module() to programmatically import a module.\n\
59\n\
60The globals argument is only used to determine the context;\n\
61they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000062should be a list of names to emulate ``from name import ...'', or an\n\
63empty list to emulate ``import name''.\n\
64When importing a module from a package, note that __import__('A.B', ...)\n\
65returns package A when fromlist is empty, but its submodule B when\n\
Neal Norwitz92e212f2006-04-03 04:48:37 +000066fromlist is not empty. Level is used to determine whether to perform \n\
67absolute or relative imports. -1 is the original strategy of attempting\n\
68both absolute and relative imports, 0 is absolute, a positive number\n\
69is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000070
Guido van Rossum1ae940a1995-01-02 19:04:15 +000071
Guido van Rossum79f25d91997-04-29 20:08:16 +000072static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000073builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +000074{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000075 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +000076}
77
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000078PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000079"abs(number) -> number\n\
80\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000081Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000082
Raymond Hettinger96229b12005-03-11 06:49:40 +000083static PyObject *
84builtin_all(PyObject *self, PyObject *v)
85{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000086 PyObject *it, *item;
87 PyObject *(*iternext)(PyObject *);
88 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +000089
Antoine Pitrouc83ea132010-05-09 14:46:46 +000090 it = PyObject_GetIter(v);
91 if (it == NULL)
92 return NULL;
93 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +000094
Antoine Pitrouc83ea132010-05-09 14:46:46 +000095 for (;;) {
96 item = iternext(it);
97 if (item == NULL)
98 break;
99 cmp = PyObject_IsTrue(item);
100 Py_DECREF(item);
101 if (cmp < 0) {
102 Py_DECREF(it);
103 return NULL;
104 }
105 if (cmp == 0) {
106 Py_DECREF(it);
107 Py_RETURN_FALSE;
108 }
109 }
110 Py_DECREF(it);
111 if (PyErr_Occurred()) {
112 if (PyErr_ExceptionMatches(PyExc_StopIteration))
113 PyErr_Clear();
114 else
115 return NULL;
116 }
117 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000118}
119
120PyDoc_STRVAR(all_doc,
121"all(iterable) -> bool\n\
122\n\
123Return True if bool(x) is True for all values x in the iterable.");
124
125static PyObject *
126builtin_any(PyObject *self, PyObject *v)
127{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000128 PyObject *it, *item;
129 PyObject *(*iternext)(PyObject *);
130 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000131
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000132 it = PyObject_GetIter(v);
133 if (it == NULL)
134 return NULL;
135 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000136
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000137 for (;;) {
138 item = iternext(it);
139 if (item == NULL)
140 break;
141 cmp = PyObject_IsTrue(item);
142 Py_DECREF(item);
143 if (cmp < 0) {
144 Py_DECREF(it);
145 return NULL;
146 }
147 if (cmp == 1) {
148 Py_DECREF(it);
149 Py_RETURN_TRUE;
150 }
151 }
152 Py_DECREF(it);
153 if (PyErr_Occurred()) {
154 if (PyErr_ExceptionMatches(PyExc_StopIteration))
155 PyErr_Clear();
156 else
157 return NULL;
158 }
159 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000160}
161
162PyDoc_STRVAR(any_doc,
163"any(iterable) -> bool\n\
164\n\
165Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000166
Guido van Rossum79f25d91997-04-29 20:08:16 +0000167static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000168builtin_apply(PyObject *self, PyObject *args)
Guido van Rossumc02e15c1991-12-16 13:03:00 +0000169{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000170 PyObject *func, *alist = NULL, *kwdict = NULL;
171 PyObject *t = NULL, *retval = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000172
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000173 if (PyErr_WarnPy3k("apply() not supported in 3.x; "
174 "use func(*args, **kwargs)", 1) < 0)
175 return NULL;
Neal Norwitz8b2bfbc2007-05-23 06:35:32 +0000176
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000177 if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))
178 return NULL;
179 if (alist != NULL) {
180 if (!PyTuple_Check(alist)) {
181 if (!PySequence_Check(alist)) {
182 PyErr_Format(PyExc_TypeError,
183 "apply() arg 2 expected sequence, found %s",
184 alist->ob_type->tp_name);
185 return NULL;
186 }
187 t = PySequence_Tuple(alist);
188 if (t == NULL)
189 return NULL;
190 alist = t;
191 }
192 }
193 if (kwdict != NULL && !PyDict_Check(kwdict)) {
194 PyErr_Format(PyExc_TypeError,
195 "apply() arg 3 expected dictionary, found %s",
196 kwdict->ob_type->tp_name);
197 goto finally;
198 }
199 retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
Barry Warsaw968f8cb1998-10-01 15:33:12 +0000200 finally:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000201 Py_XDECREF(t);
202 return retval;
Guido van Rossumc02e15c1991-12-16 13:03:00 +0000203}
204
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000205PyDoc_STRVAR(apply_doc,
Fred Drakef1fbc622001-01-12 17:05:05 +0000206"apply(object[, args[, kwargs]]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000207\n\
Fred Drake7b912121999-12-23 14:16:55 +0000208Call a callable object with positional arguments taken from the tuple args,\n\
209and keyword arguments taken from the optional dictionary kwargs.\n\
Raymond Hettingerff41c482003-04-06 09:01:11 +0000210Note that classes are callable, as are instances with a __call__() method.\n\
211\n\
212Deprecated since release 2.3. Instead, use the extended call syntax:\n\
213 function(*args, **keywords).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000214
215
Guido van Rossum79f25d91997-04-29 20:08:16 +0000216static PyObject *
Eric Smith3cd81942008-02-22 16:30:22 +0000217builtin_bin(PyObject *self, PyObject *v)
218{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000219 return PyNumber_ToBase(v, 2);
Eric Smith3cd81942008-02-22 16:30:22 +0000220}
221
222PyDoc_STRVAR(bin_doc,
223"bin(number) -> string\n\
224\n\
225Return the binary representation of an integer or long integer.");
226
227
228static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000229builtin_callable(PyObject *self, PyObject *v)
Guido van Rossum2d951851994-08-29 12:52:16 +0000230{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000231 return PyBool_FromLong((long)PyCallable_Check(v));
Guido van Rossum2d951851994-08-29 12:52:16 +0000232}
233
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000234PyDoc_STRVAR(callable_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000235"callable(object) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000236\n\
237Return whether the object is callable (i.e., some kind of function).\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000238Note that classes are callable, as are instances with a __call__() method.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000239
240
Guido van Rossum79f25d91997-04-29 20:08:16 +0000241static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000242builtin_filter(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000243{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000244 PyObject *func, *seq, *result, *it, *arg;
245 Py_ssize_t len; /* guess for result list size */
246 register Py_ssize_t j;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000247
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000248 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
249 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000250
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000251 /* Strings and tuples return a result of the same type. */
252 if (PyString_Check(seq))
253 return filterstring(func, seq);
Martin v. Löwis8afd7572003-01-25 22:46:11 +0000254#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000255 if (PyUnicode_Check(seq))
256 return filterunicode(func, seq);
Martin v. Löwis8afd7572003-01-25 22:46:11 +0000257#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000258 if (PyTuple_Check(seq))
259 return filtertuple(func, seq);
Tim Peters0e57abf2001-05-02 07:39:38 +0000260
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000261 /* Pre-allocate argument list tuple. */
262 arg = PyTuple_New(1);
263 if (arg == NULL)
264 return NULL;
Georg Brandle35b6572005-07-19 22:20:20 +0000265
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000266 /* Get iterator. */
267 it = PyObject_GetIter(seq);
268 if (it == NULL)
269 goto Fail_arg;
Tim Peters0e57abf2001-05-02 07:39:38 +0000270
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000271 /* Guess a result list size. */
272 len = _PyObject_LengthHint(seq, 8);
273 if (len == -1)
274 goto Fail_it;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000275
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000276 /* Get a result list. */
277 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
278 /* Eww - can modify the list in-place. */
279 Py_INCREF(seq);
280 result = seq;
281 }
282 else {
283 result = PyList_New(len);
284 if (result == NULL)
285 goto Fail_it;
286 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000287
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000288 /* Build the result list. */
289 j = 0;
290 for (;;) {
291 PyObject *item;
292 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000293
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000294 item = PyIter_Next(it);
295 if (item == NULL) {
296 if (PyErr_Occurred())
297 goto Fail_result_it;
298 break;
299 }
Guido van Rossumdc4b93d1993-10-27 14:56:44 +0000300
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000301 if (func == (PyObject *)&PyBool_Type || func == Py_None) {
302 ok = PyObject_IsTrue(item);
303 }
304 else {
305 PyObject *good;
306 PyTuple_SET_ITEM(arg, 0, item);
307 good = PyObject_Call(func, arg, NULL);
308 PyTuple_SET_ITEM(arg, 0, NULL);
309 if (good == NULL) {
310 Py_DECREF(item);
311 goto Fail_result_it;
312 }
313 ok = PyObject_IsTrue(good);
314 Py_DECREF(good);
315 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +0200316 if (ok > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000317 if (j < len)
318 PyList_SET_ITEM(result, j, item);
319 else {
320 int status = PyList_Append(result, item);
321 Py_DECREF(item);
322 if (status < 0)
323 goto Fail_result_it;
324 }
325 ++j;
326 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +0200327 else {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000328 Py_DECREF(item);
Antoine Pitrouc5bef752012-08-15 23:16:51 +0200329 if (ok < 0)
330 goto Fail_result_it;
331 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000332 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000333
Guido van Rossum12d12c51993-10-26 17:58:25 +0000334
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000335 /* Cut back result list if len is too big. */
336 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
337 goto Fail_result_it;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000338
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000339 Py_DECREF(it);
340 Py_DECREF(arg);
341 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000342
Tim Peters0e57abf2001-05-02 07:39:38 +0000343Fail_result_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000344 Py_DECREF(result);
Tim Peters0e57abf2001-05-02 07:39:38 +0000345Fail_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000346 Py_DECREF(it);
Guido van Rossumc7903a12002-08-16 07:04:56 +0000347Fail_arg:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000348 Py_DECREF(arg);
349 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000350}
351
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000352PyDoc_STRVAR(filter_doc,
Tim Petersd50e5442002-03-09 00:06:26 +0000353"filter(function or None, sequence) -> list, tuple, or string\n"
354"\n"
355"Return those items of sequence for which function(item) is true. If\n"
356"function is None, return the items that are true. If sequence is a tuple\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000357"or string, return the same type, else return a list.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000358
Guido van Rossum79f25d91997-04-29 20:08:16 +0000359static PyObject *
Eric Smitha9f7d622008-02-17 19:46:49 +0000360builtin_format(PyObject *self, PyObject *args)
361{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000362 PyObject *value;
363 PyObject *format_spec = NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +0000364
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000365 if (!PyArg_ParseTuple(args, "O|O:format", &value, &format_spec))
366 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +0000367
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000368 return PyObject_Format(value, format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +0000369}
370
371PyDoc_STRVAR(format_doc,
372"format(value[, format_spec]) -> string\n\
373\n\
374Returns value.__format__(format_spec)\n\
375format_spec defaults to \"\"");
376
377static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000378builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000379{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000380 long x;
381 char s[1];
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000382
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000383 if (!PyArg_ParseTuple(args, "l:chr", &x))
384 return NULL;
385 if (x < 0 || x >= 256) {
386 PyErr_SetString(PyExc_ValueError,
387 "chr() arg not in range(256)");
388 return NULL;
389 }
390 s[0] = (char)x;
391 return PyString_FromStringAndSize(s, 1);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000392}
393
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000394PyDoc_STRVAR(chr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000395"chr(i) -> character\n\
396\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000397Return a string of one character with ordinal i; 0 <= i < 256.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000398
399
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000400#ifdef Py_USING_UNICODE
Guido van Rossum79f25d91997-04-29 20:08:16 +0000401static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000402builtin_unichr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000403{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000404 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000405
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000406 if (!PyArg_ParseTuple(args, "i:unichr", &x))
407 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000408
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000409 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000410}
411
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000412PyDoc_STRVAR(unichr_doc,
Fred Drake078b24f2000-04-13 02:42:50 +0000413"unichr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000414\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000415Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000416#endif
Guido van Rossum09095f32000-03-10 23:00:52 +0000417
418
419static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000420builtin_cmp(PyObject *self, PyObject *args)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000421{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000422 PyObject *a, *b;
423 int c;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000424
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000425 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
426 return NULL;
427 if (PyObject_Cmp(a, b, &c) < 0)
428 return NULL;
429 return PyInt_FromLong((long)c);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000430}
431
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000432PyDoc_STRVAR(cmp_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000433"cmp(x, y) -> integer\n\
434\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000435Return negative if x<y, zero if x==y, positive if x>y.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000436
437
Guido van Rossum79f25d91997-04-29 20:08:16 +0000438static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000439builtin_coerce(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000440{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000441 PyObject *v, *w;
442 PyObject *res;
Guido van Rossum5524a591995-01-10 15:26:20 +0000443
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000444 if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
445 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +0000446
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000447 if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
448 return NULL;
449 if (PyNumber_Coerce(&v, &w) < 0)
450 return NULL;
451 res = PyTuple_Pack(2, v, w);
452 Py_DECREF(v);
453 Py_DECREF(w);
454 return res;
Guido van Rossum04691fc1992-08-12 15:35:34 +0000455}
456
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000457PyDoc_STRVAR(coerce_doc,
Martin v. Löwis8d494f32004-08-25 10:42:41 +0000458"coerce(x, y) -> (x1, y1)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000459\n\
Martin v. Löwis8d494f32004-08-25 10:42:41 +0000460Return a tuple consisting of the two numeric arguments converted to\n\
461a common type, using the same rules as used by arithmetic operations.\n\
462If coercion is not possible, raise TypeError.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000463
Guido van Rossum79f25d91997-04-29 20:08:16 +0000464static PyObject *
Georg Brandl5240d742007-03-13 20:46:32 +0000465builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000466{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000467 char *str;
468 char *filename;
469 char *startstr;
470 int mode = -1;
471 int dont_inherit = 0;
472 int supplied_flags = 0;
473 int is_ast;
474 PyCompilerFlags cf;
475 PyObject *result = NULL, *cmd, *tmp = NULL;
476 Py_ssize_t length;
477 static char *kwlist[] = {"source", "filename", "mode", "flags",
478 "dont_inherit", NULL};
479 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000480
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000481 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
482 kwlist, &cmd, &filename, &startstr,
483 &supplied_flags, &dont_inherit))
484 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000485
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000486 cf.cf_flags = supplied_flags;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000487
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000488 if (supplied_flags &
489 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
490 {
491 PyErr_SetString(PyExc_ValueError,
492 "compile(): unrecognised flags");
493 return NULL;
494 }
495 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Georg Brandlfc8eef32008-03-28 12:11:56 +0000496
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000497 if (!dont_inherit) {
498 PyEval_MergeCompilerFlags(&cf);
499 }
Georg Brandlfc8eef32008-03-28 12:11:56 +0000500
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000501 if (strcmp(startstr, "exec") == 0)
502 mode = 0;
503 else if (strcmp(startstr, "eval") == 0)
504 mode = 1;
505 else if (strcmp(startstr, "single") == 0)
506 mode = 2;
507 else {
508 PyErr_SetString(PyExc_ValueError,
509 "compile() arg 3 must be 'exec', 'eval' or 'single'");
510 return NULL;
511 }
Georg Brandlf2bfd542008-03-29 13:24:23 +0000512
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000513 is_ast = PyAST_Check(cmd);
514 if (is_ast == -1)
515 return NULL;
516 if (is_ast) {
517 if (supplied_flags & PyCF_ONLY_AST) {
518 Py_INCREF(cmd);
519 result = cmd;
520 }
521 else {
522 PyArena *arena;
523 mod_ty mod;
Georg Brandlfc8eef32008-03-28 12:11:56 +0000524
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000525 arena = PyArena_New();
Stefan Kraha8857af2012-08-20 17:31:22 +0200526 if (arena == NULL)
527 return NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000528 mod = PyAST_obj2mod(cmd, arena, mode);
529 if (mod == NULL) {
530 PyArena_Free(arena);
531 return NULL;
532 }
533 result = (PyObject*)PyAST_Compile(mod, filename,
534 &cf, arena);
535 PyArena_Free(arena);
536 }
537 return result;
538 }
Georg Brandlfc8eef32008-03-28 12:11:56 +0000539
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000540#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000541 if (PyUnicode_Check(cmd)) {
542 tmp = PyUnicode_AsUTF8String(cmd);
543 if (tmp == NULL)
544 return NULL;
545 cmd = tmp;
546 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
547 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000548#endif
Tim Peters6cd6a822001-08-17 22:11:27 +0000549
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000550 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))
551 goto cleanup;
552 if ((size_t)length != strlen(str)) {
553 PyErr_SetString(PyExc_TypeError,
554 "compile() expected string without null bytes");
555 goto cleanup;
556 }
557 result = Py_CompileStringFlags(str, filename, start[mode], &cf);
Neal Norwitz3a9a3e72005-11-27 20:38:31 +0000558cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000559 Py_XDECREF(tmp);
560 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000561}
562
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000563PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000564"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000565\n\
566Compile the source string (a Python module, statement or expression)\n\
567into a code object that can be executed by the exec statement or eval().\n\
568The filename will be used for run-time error messages.\n\
569The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000570single (interactive) statement, or 'eval' to compile an expression.\n\
571The flags argument, if present, controls which future statements influence\n\
572the compilation of the code.\n\
573The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
574the effects of any future statements in effect in the code calling\n\
575compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000576in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000577
Guido van Rossum79f25d91997-04-29 20:08:16 +0000578static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000579builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000580{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000581 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000582
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000583 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
584 return NULL;
585 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000586}
587
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000588PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000589"dir([object]) -> list of strings\n"
590"\n"
Georg Brandl871f1bc2007-03-12 13:17:36 +0000591"If called without an argument, return the names in the current scope.\n"
592"Else, return an alphabetized list of names comprising (some of) the attributes\n"
593"of the given object, and of attributes reachable from it.\n"
594"If the object supplies a method named __dir__, it will be used; otherwise\n"
595"the default dir() logic is used and returns:\n"
596" for a module object: the module's attributes.\n"
597" for a class object: its attributes, and recursively the attributes\n"
598" of its bases.\n"
Georg Brandl3bb15672007-03-13 07:23:16 +0000599" for any other object: its attributes, its class's attributes, and\n"
Georg Brandl871f1bc2007-03-12 13:17:36 +0000600" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000601
Guido van Rossum79f25d91997-04-29 20:08:16 +0000602static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000603builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000604{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000605 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000606
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000607 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
608 return NULL;
609 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000610}
611
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000612PyDoc_STRVAR(divmod_doc,
Raymond Hettinger39540a02011-07-19 11:59:20 -0700613"divmod(x, y) -> (quotient, remainder)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000614\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000615Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000616
617
Guido van Rossum79f25d91997-04-29 20:08:16 +0000618static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000619builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000620{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000621 PyObject *cmd, *result, *tmp = NULL;
622 PyObject *globals = Py_None, *locals = Py_None;
623 char *str;
624 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000625
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000626 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
627 return NULL;
628 if (locals != Py_None && !PyMapping_Check(locals)) {
629 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
630 return NULL;
631 }
632 if (globals != Py_None && !PyDict_Check(globals)) {
633 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
634 "globals must be a real dict; try eval(expr, {}, mapping)"
635 : "globals must be a dict");
636 return NULL;
637 }
638 if (globals == Py_None) {
639 globals = PyEval_GetGlobals();
640 if (locals == Py_None)
641 locals = PyEval_GetLocals();
642 }
643 else if (locals == Py_None)
644 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000645
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000646 if (globals == NULL || locals == NULL) {
647 PyErr_SetString(PyExc_TypeError,
648 "eval must be given globals and locals "
649 "when called without a frame");
650 return NULL;
651 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000652
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000653 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
654 if (PyDict_SetItemString(globals, "__builtins__",
655 PyEval_GetBuiltins()) != 0)
656 return NULL;
657 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000658
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000659 if (PyCode_Check(cmd)) {
660 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
661 PyErr_SetString(PyExc_TypeError,
662 "code object passed to eval() may not contain free variables");
663 return NULL;
664 }
665 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
666 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000667
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000668 if (!PyString_Check(cmd) &&
669 !PyUnicode_Check(cmd)) {
670 PyErr_SetString(PyExc_TypeError,
671 "eval() arg 1 must be a string or code object");
672 return NULL;
673 }
674 cf.cf_flags = 0;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000675
676#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000677 if (PyUnicode_Check(cmd)) {
678 tmp = PyUnicode_AsUTF8String(cmd);
679 if (tmp == NULL)
680 return NULL;
681 cmd = tmp;
682 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
683 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000684#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000685 if (PyString_AsStringAndSize(cmd, &str, NULL)) {
686 Py_XDECREF(tmp);
687 return NULL;
688 }
689 while (*str == ' ' || *str == '\t')
690 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000691
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000692 (void)PyEval_MergeCompilerFlags(&cf);
693 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
694 Py_XDECREF(tmp);
695 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000696}
697
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000698PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000699"eval(source[, globals[, locals]]) -> value\n\
700\n\
701Evaluate the source in the context of globals and locals.\n\
702The source may be a string representing a Python expression\n\
703or a code object as returned by compile().\n\
Neal Norwitz477ca1c2006-09-05 02:25:41 +0000704The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000705defaulting to the current globals and locals.\n\
706If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000707
708
Guido van Rossum79f25d91997-04-29 20:08:16 +0000709static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000710builtin_execfile(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000711{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000712 char *filename;
713 PyObject *globals = Py_None, *locals = Py_None;
714 PyObject *res;
715 FILE* fp = NULL;
716 PyCompilerFlags cf;
717 int exists;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000718
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000719 if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
720 1) < 0)
721 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +0000722
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000723 if (!PyArg_ParseTuple(args, "s|O!O:execfile",
724 &filename,
725 &PyDict_Type, &globals,
726 &locals))
727 return NULL;
728 if (locals != Py_None && !PyMapping_Check(locals)) {
729 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
730 return NULL;
731 }
732 if (globals == Py_None) {
733 globals = PyEval_GetGlobals();
734 if (locals == Py_None)
735 locals = PyEval_GetLocals();
736 }
737 else if (locals == Py_None)
738 locals = globals;
739 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
740 if (PyDict_SetItemString(globals, "__builtins__",
741 PyEval_GetBuiltins()) != 0)
742 return NULL;
743 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000744
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000745 exists = 0;
746 /* Test for existence or directory. */
Martin v. Löwis3484a182002-03-09 12:07:51 +0000747#if defined(PLAN9)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000748 {
749 Dir *d;
Martin v. Löwis3484a182002-03-09 12:07:51 +0000750
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000751 if ((d = dirstat(filename))!=nil) {
752 if(d->mode & DMDIR)
753 werrstr("is a directory");
754 else
755 exists = 1;
756 free(d);
757 }
758 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000759#elif defined(RISCOS)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000760 if (object_exists(filename)) {
761 if (isdir(filename))
762 errno = EISDIR;
763 else
764 exists = 1;
765 }
766#else /* standard Posix */
767 {
768 struct stat s;
769 if (stat(filename, &s) == 0) {
770 if (S_ISDIR(s.st_mode))
771# if defined(PYOS_OS2) && defined(PYCC_VACPP)
772 errno = EOS2ERR;
773# else
774 errno = EISDIR;
775# endif
776 else
777 exists = 1;
778 }
779 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000780#endif
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000781
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000782 if (exists) {
783 Py_BEGIN_ALLOW_THREADS
784 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
785 Py_END_ALLOW_THREADS
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000786
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000787 if (fp == NULL) {
788 exists = 0;
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000789 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000790 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000791
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000792 if (!exists) {
793 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
794 return NULL;
795 }
796 cf.cf_flags = 0;
797 if (PyEval_MergeCompilerFlags(&cf))
798 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
799 locals, 1, &cf);
800 else
801 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
802 locals, 1);
803 return res;
Guido van Rossum0f61f8a1992-02-25 18:55:05 +0000804}
805
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000806PyDoc_STRVAR(execfile_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000807"execfile(filename[, globals[, locals]])\n\
808\n\
809Read and execute a Python script from a file.\n\
810The globals and locals are dictionaries, defaulting to the current\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000811globals and locals. If only globals is given, locals defaults to it.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000812
813
Guido van Rossum79f25d91997-04-29 20:08:16 +0000814static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000815builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000816{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000817 PyObject *v, *result, *dflt = NULL;
818 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000819
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000820 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
821 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000822#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000823 if (PyUnicode_Check(name)) {
824 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
825 if (name == NULL)
826 return NULL;
827 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000828#endif
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000829
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000830 if (!PyString_Check(name)) {
831 PyErr_SetString(PyExc_TypeError,
832 "getattr(): attribute name must be string");
833 return NULL;
834 }
835 result = PyObject_GetAttr(v, name);
836 if (result == NULL && dflt != NULL &&
837 PyErr_ExceptionMatches(PyExc_AttributeError))
838 {
839 PyErr_Clear();
840 Py_INCREF(dflt);
841 result = dflt;
842 }
843 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000844}
845
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000846PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000847"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000848\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000849Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
850When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000851exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000852
853
Guido van Rossum79f25d91997-04-29 20:08:16 +0000854static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000855builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000856{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000857 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000858
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000859 d = PyEval_GetGlobals();
860 Py_XINCREF(d);
861 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000862}
863
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000864PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000865"globals() -> dictionary\n\
866\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000867Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000868
869
Guido van Rossum79f25d91997-04-29 20:08:16 +0000870static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000871builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000872{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000873 PyObject *v;
874 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000875
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000876 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
877 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000878#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000879 if (PyUnicode_Check(name)) {
880 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
881 if (name == NULL)
882 return NULL;
883 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000884#endif
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000885
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000886 if (!PyString_Check(name)) {
887 PyErr_SetString(PyExc_TypeError,
888 "hasattr(): attribute name must be string");
889 return NULL;
890 }
891 v = PyObject_GetAttr(v, name);
892 if (v == NULL) {
893 if (!PyErr_ExceptionMatches(PyExc_Exception))
894 return NULL;
895 else {
896 PyErr_Clear();
897 Py_INCREF(Py_False);
898 return Py_False;
899 }
900 }
901 Py_DECREF(v);
902 Py_INCREF(Py_True);
903 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000904}
905
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000906PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000907"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000908\n\
909Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000910(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000911
912
Guido van Rossum79f25d91997-04-29 20:08:16 +0000913static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000914builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000915{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000916 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000917}
918
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000919PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000920"id(object) -> integer\n\
921\n\
922Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000923simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000924
925
Guido van Rossum79f25d91997-04-29 20:08:16 +0000926static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000927builtin_map(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000928{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000929 typedef struct {
930 PyObject *it; /* the iterator object */
931 int saw_StopIteration; /* bool: did the iterator end? */
932 } sequence;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000933
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000934 PyObject *func, *result;
935 sequence *seqs = NULL, *sqp;
936 Py_ssize_t n, len;
937 register int i, j;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000938
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000939 n = PyTuple_Size(args);
940 if (n < 2) {
941 PyErr_SetString(PyExc_TypeError,
942 "map() requires at least two args");
943 return NULL;
944 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000945
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000946 func = PyTuple_GetItem(args, 0);
947 n--;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000948
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000949 if (func == Py_None) {
950 if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
951 "use list(...)", 1) < 0)
952 return NULL;
953 if (n == 1) {
954 /* map(None, S) is the same as list(S). */
955 return PySequence_List(PyTuple_GetItem(args, 1));
956 }
957 }
Guido van Rossumfa4ac711998-07-10 17:37:30 +0000958
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000959 /* Get space for sequence descriptors. Must NULL out the iterator
960 * pointers so that jumping to Fail_2 later doesn't see trash.
961 */
962 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
963 PyErr_NoMemory();
964 return NULL;
965 }
966 for (i = 0; i < n; ++i) {
967 seqs[i].it = (PyObject*)NULL;
968 seqs[i].saw_StopIteration = 0;
969 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000970
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000971 /* Do a first pass to obtain iterators for the arguments, and set len
972 * to the largest of their lengths.
973 */
974 len = 0;
975 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
976 PyObject *curseq;
977 Py_ssize_t curlen;
Guido van Rossumad991772001-01-12 16:03:05 +0000978
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000979 /* Get iterator. */
980 curseq = PyTuple_GetItem(args, i+1);
981 sqp->it = PyObject_GetIter(curseq);
982 if (sqp->it == NULL) {
983 static char errmsg[] =
984 "argument %d to map() must support iteration";
985 char errbuf[sizeof(errmsg) + 25];
986 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
987 PyErr_SetString(PyExc_TypeError, errbuf);
988 goto Fail_2;
989 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000990
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000991 /* Update len. */
992 curlen = _PyObject_LengthHint(curseq, 8);
993 if (curlen > len)
994 len = curlen;
995 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000996
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000997 /* Get space for the result list. */
998 if ((result = (PyObject *) PyList_New(len)) == NULL)
999 goto Fail_2;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001000
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001001 /* Iterate over the sequences until all have stopped. */
1002 for (i = 0; ; ++i) {
1003 PyObject *alist, *item=NULL, *value;
1004 int numactive = 0;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001005
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001006 if (func == Py_None && n == 1)
1007 alist = NULL;
1008 else if ((alist = PyTuple_New(n)) == NULL)
1009 goto Fail_1;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001010
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001011 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
1012 if (sqp->saw_StopIteration) {
1013 Py_INCREF(Py_None);
1014 item = Py_None;
1015 }
1016 else {
1017 item = PyIter_Next(sqp->it);
1018 if (item)
1019 ++numactive;
1020 else {
1021 if (PyErr_Occurred()) {
1022 Py_XDECREF(alist);
1023 goto Fail_1;
1024 }
1025 Py_INCREF(Py_None);
1026 item = Py_None;
1027 sqp->saw_StopIteration = 1;
1028 }
1029 }
1030 if (alist)
1031 PyTuple_SET_ITEM(alist, j, item);
1032 else
1033 break;
1034 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001035
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001036 if (!alist)
1037 alist = item;
Guido van Rossum2d951851994-08-29 12:52:16 +00001038
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001039 if (numactive == 0) {
1040 Py_DECREF(alist);
1041 break;
1042 }
Guido van Rossum2d951851994-08-29 12:52:16 +00001043
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001044 if (func == Py_None)
1045 value = alist;
1046 else {
1047 value = PyEval_CallObject(func, alist);
1048 Py_DECREF(alist);
1049 if (value == NULL)
1050 goto Fail_1;
1051 }
1052 if (i >= len) {
1053 int status = PyList_Append(result, value);
1054 Py_DECREF(value);
1055 if (status < 0)
1056 goto Fail_1;
1057 }
1058 else if (PyList_SetItem(result, i, value) < 0)
1059 goto Fail_1;
1060 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001061
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001062 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
1063 goto Fail_1;
Guido van Rossumfa4ac711998-07-10 17:37:30 +00001064
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001065 goto Succeed;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001066
Guido van Rossum12d12c51993-10-26 17:58:25 +00001067Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001068 Py_DECREF(result);
Guido van Rossum12d12c51993-10-26 17:58:25 +00001069Fail_2:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001070 result = NULL;
Tim Peters4e9afdc2001-05-03 23:54:49 +00001071Succeed:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001072 assert(seqs);
1073 for (i = 0; i < n; ++i)
1074 Py_XDECREF(seqs[i].it);
1075 PyMem_DEL(seqs);
1076 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001077}
1078
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001079PyDoc_STRVAR(map_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001080"map(function, sequence[, sequence, ...]) -> list\n\
1081\n\
1082Return a list of the results of applying the function to the items of\n\
1083the argument sequence(s). If more than one sequence is given, the\n\
1084function is called with an argument list consisting of the corresponding\n\
1085item of each sequence, substituting None for missing values when not all\n\
1086sequences have the same length. If the function is None, return a list of\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001087the items of the sequence (or a list of tuples if more than one sequence).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001088
1089
Guido van Rossum79f25d91997-04-29 20:08:16 +00001090static PyObject *
Georg Brandl28e08732008-04-30 19:47:09 +00001091builtin_next(PyObject *self, PyObject *args)
1092{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001093 PyObject *it, *res;
1094 PyObject *def = NULL;
Georg Brandl28e08732008-04-30 19:47:09 +00001095
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001096 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1097 return NULL;
1098 if (!PyIter_Check(it)) {
1099 PyErr_Format(PyExc_TypeError,
1100 "%.200s object is not an iterator",
1101 it->ob_type->tp_name);
1102 return NULL;
1103 }
1104
1105 res = (*it->ob_type->tp_iternext)(it);
1106 if (res != NULL) {
1107 return res;
1108 } else if (def != NULL) {
1109 if (PyErr_Occurred()) {
1110 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
1111 return NULL;
1112 PyErr_Clear();
1113 }
1114 Py_INCREF(def);
1115 return def;
1116 } else if (PyErr_Occurred()) {
1117 return NULL;
1118 } else {
1119 PyErr_SetNone(PyExc_StopIteration);
1120 return NULL;
1121 }
Georg Brandl28e08732008-04-30 19:47:09 +00001122}
1123
1124PyDoc_STRVAR(next_doc,
1125"next(iterator[, default])\n\
1126\n\
1127Return the next item from the iterator. If default is given and the iterator\n\
1128is exhausted, it is returned instead of raising StopIteration.");
1129
1130
1131static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001132builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001133{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001134 PyObject *v;
1135 PyObject *name;
1136 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001137
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001138 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1139 return NULL;
1140 if (PyObject_SetAttr(v, name, value) != 0)
1141 return NULL;
1142 Py_INCREF(Py_None);
1143 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001144}
1145
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001146PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001147"setattr(object, name, value)\n\
1148\n\
1149Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001150``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001151
1152
Guido van Rossum79f25d91997-04-29 20:08:16 +00001153static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001154builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001155{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001156 PyObject *v;
1157 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001158
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001159 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1160 return NULL;
1161 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1162 return NULL;
1163 Py_INCREF(Py_None);
1164 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001165}
1166
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001167PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001168"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001169\n\
1170Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001171``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001172
1173
Guido van Rossum79f25d91997-04-29 20:08:16 +00001174static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001175builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001176{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001177 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001178
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001179 x = PyObject_Hash(v);
1180 if (x == -1)
1181 return NULL;
1182 return PyInt_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001183}
1184
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001185PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001186"hash(object) -> integer\n\
1187\n\
1188Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001189the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001190
1191
Guido van Rossum79f25d91997-04-29 20:08:16 +00001192static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001193builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001194{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001195 PyNumberMethods *nb;
1196 PyObject *res;
Benjamin Petersonc6d64ec2008-05-17 20:09:42 +00001197
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001198 if ((nb = v->ob_type->tp_as_number) == NULL ||
1199 nb->nb_hex == NULL) {
1200 PyErr_SetString(PyExc_TypeError,
1201 "hex() argument can't be converted to hex");
1202 return NULL;
1203 }
1204 res = (*nb->nb_hex)(v);
1205 if (res && !PyString_Check(res)) {
1206 PyErr_Format(PyExc_TypeError,
1207 "__hex__ returned non-string (type %.200s)",
1208 res->ob_type->tp_name);
1209 Py_DECREF(res);
1210 return NULL;
1211 }
1212 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001213}
1214
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001215PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001216"hex(number) -> string\n\
1217\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001218Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001219
1220
Tim Petersdbd9ba62000-07-09 03:09:57 +00001221static PyObject *builtin_raw_input(PyObject *, PyObject *);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001222
Guido van Rossum79f25d91997-04-29 20:08:16 +00001223static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001224builtin_input(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001225{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001226 PyObject *line;
1227 char *str;
1228 PyObject *res;
1229 PyObject *globals, *locals;
1230 PyCompilerFlags cf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001231
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001232 line = builtin_raw_input(self, args);
1233 if (line == NULL)
1234 return line;
1235 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1236 return NULL;
1237 while (*str == ' ' || *str == '\t')
1238 str++;
1239 globals = PyEval_GetGlobals();
1240 locals = PyEval_GetLocals();
1241 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1242 if (PyDict_SetItemString(globals, "__builtins__",
1243 PyEval_GetBuiltins()) != 0)
1244 return NULL;
1245 }
1246 cf.cf_flags = 0;
1247 PyEval_MergeCompilerFlags(&cf);
1248 res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1249 Py_DECREF(line);
1250 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001251}
1252
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001253PyDoc_STRVAR(input_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001254"input([prompt]) -> value\n\
1255\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001256Equivalent to eval(raw_input(prompt)).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001257
1258
Guido van Rossume8811f81997-02-14 15:48:05 +00001259static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001260builtin_intern(PyObject *self, PyObject *args)
Guido van Rossume8811f81997-02-14 15:48:05 +00001261{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001262 PyObject *s;
1263 if (!PyArg_ParseTuple(args, "S:intern", &s))
1264 return NULL;
1265 if (!PyString_CheckExact(s)) {
1266 PyErr_SetString(PyExc_TypeError,
1267 "can't intern subclass of string");
1268 return NULL;
1269 }
1270 Py_INCREF(s);
1271 PyString_InternInPlace(&s);
1272 return s;
Guido van Rossume8811f81997-02-14 15:48:05 +00001273}
1274
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001275PyDoc_STRVAR(intern_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001276"intern(string) -> string\n\
1277\n\
1278``Intern'' the given string. This enters the string in the (global)\n\
1279table of interned strings whose purpose is to speed up dictionary lookups.\n\
1280Return the string itself or the previously interned string object with the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001281same value.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001282
1283
Guido van Rossum79f25d91997-04-29 20:08:16 +00001284static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001285builtin_iter(PyObject *self, PyObject *args)
1286{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001287 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001288
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001289 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1290 return NULL;
1291 if (w == NULL)
1292 return PyObject_GetIter(v);
1293 if (!PyCallable_Check(v)) {
1294 PyErr_SetString(PyExc_TypeError,
1295 "iter(v, w): v must be callable");
1296 return NULL;
1297 }
1298 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001299}
1300
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001301PyDoc_STRVAR(iter_doc,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001302"iter(collection) -> iterator\n\
1303iter(callable, sentinel) -> iterator\n\
1304\n\
1305Get an iterator from an object. In the first form, the argument must\n\
1306supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001307In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001308
1309
1310static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001311builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001312{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001313 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001314
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001315 res = PyObject_Size(v);
1316 if (res < 0 && PyErr_Occurred())
1317 return NULL;
1318 return PyInt_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001319}
1320
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001321PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001322"len(object) -> integer\n\
1323\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001324Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001325
1326
Guido van Rossum79f25d91997-04-29 20:08:16 +00001327static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001328builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001329{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001330 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001331
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001332 d = PyEval_GetLocals();
1333 Py_XINCREF(d);
1334 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001335}
1336
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001337PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001338"locals() -> dictionary\n\
1339\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001340Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001341
1342
Guido van Rossum79f25d91997-04-29 20:08:16 +00001343static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001344min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001345{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001346 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1347 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001348
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001349 if (PyTuple_Size(args) > 1)
1350 v = args;
1351 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1352 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001353
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001354 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1355 keyfunc = PyDict_GetItemString(kwds, "key");
1356 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1357 PyErr_Format(PyExc_TypeError,
1358 "%s() got an unexpected keyword argument", name);
1359 return NULL;
1360 }
1361 Py_INCREF(keyfunc);
1362 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001363
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001364 it = PyObject_GetIter(v);
1365 if (it == NULL) {
1366 Py_XDECREF(keyfunc);
1367 return NULL;
1368 }
Tim Petersc3074532001-05-03 07:00:32 +00001369
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001370 maxitem = NULL; /* the result */
1371 maxval = NULL; /* the value associated with the result */
1372 while (( item = PyIter_Next(it) )) {
1373 /* get the value from the key function */
1374 if (keyfunc != NULL) {
1375 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1376 if (val == NULL)
1377 goto Fail_it_item;
1378 }
1379 /* no key function; the value is the item */
1380 else {
1381 val = item;
1382 Py_INCREF(val);
1383 }
Tim Petersc3074532001-05-03 07:00:32 +00001384
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001385 /* maximum value and item are unset; set them */
1386 if (maxval == NULL) {
1387 maxitem = item;
1388 maxval = val;
1389 }
1390 /* maximum value and item are set; update them as necessary */
1391 else {
1392 int cmp = PyObject_RichCompareBool(val, maxval, op);
1393 if (cmp < 0)
1394 goto Fail_it_item_and_val;
1395 else if (cmp > 0) {
1396 Py_DECREF(maxval);
1397 Py_DECREF(maxitem);
1398 maxval = val;
1399 maxitem = item;
1400 }
1401 else {
1402 Py_DECREF(item);
1403 Py_DECREF(val);
1404 }
1405 }
1406 }
1407 if (PyErr_Occurred())
1408 goto Fail_it;
1409 if (maxval == NULL) {
1410 PyErr_Format(PyExc_ValueError,
1411 "%s() arg is an empty sequence", name);
1412 assert(maxitem == NULL);
1413 }
1414 else
1415 Py_DECREF(maxval);
1416 Py_DECREF(it);
1417 Py_XDECREF(keyfunc);
1418 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001419
1420Fail_it_item_and_val:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001421 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001422Fail_it_item:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001423 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001424Fail_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001425 Py_XDECREF(maxval);
1426 Py_XDECREF(maxitem);
1427 Py_DECREF(it);
1428 Py_XDECREF(keyfunc);
1429 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001430}
1431
Guido van Rossum79f25d91997-04-29 20:08:16 +00001432static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001433builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001434{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001435 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001436}
1437
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001438PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001439"min(iterable[, key=func]) -> value\n\
1440min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001441\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001442With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001443With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001444
1445
Guido van Rossum79f25d91997-04-29 20:08:16 +00001446static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001447builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001448{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001449 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001450}
1451
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001452PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001453"max(iterable[, key=func]) -> value\n\
1454max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001455\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001456With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001457With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001458
1459
Guido van Rossum79f25d91997-04-29 20:08:16 +00001460static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001461builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001462{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001463 PyNumberMethods *nb;
1464 PyObject *res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001465
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001466 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1467 nb->nb_oct == NULL) {
1468 PyErr_SetString(PyExc_TypeError,
1469 "oct() argument can't be converted to oct");
1470 return NULL;
1471 }
1472 res = (*nb->nb_oct)(v);
1473 if (res && !PyString_Check(res)) {
1474 PyErr_Format(PyExc_TypeError,
1475 "__oct__ returned non-string (type %.200s)",
1476 res->ob_type->tp_name);
1477 Py_DECREF(res);
1478 return NULL;
1479 }
1480 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001481}
1482
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001483PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001484"oct(number) -> string\n\
1485\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001486Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001487
1488
Guido van Rossum79f25d91997-04-29 20:08:16 +00001489static PyObject *
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001490builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
1491{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001492 return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001493}
1494
1495PyDoc_STRVAR(open_doc,
1496"open(name[, mode[, buffering]]) -> file object\n\
1497\n\
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00001498Open a file using the file() type, returns a file object. This is the\n\
Philip Jenveydd0388a2009-05-28 03:12:16 +00001499preferred way to open a file. See file.__doc__ for further information.");
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001500
1501
1502static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001503builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001504{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001505 long ord;
1506 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001507
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001508 if (PyString_Check(obj)) {
1509 size = PyString_GET_SIZE(obj);
1510 if (size == 1) {
1511 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1512 return PyInt_FromLong(ord);
1513 }
1514 } else if (PyByteArray_Check(obj)) {
1515 size = PyByteArray_GET_SIZE(obj);
1516 if (size == 1) {
1517 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1518 return PyInt_FromLong(ord);
1519 }
Christian Heimes1a6387e2008-03-26 12:49:49 +00001520
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001521#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001522 } else if (PyUnicode_Check(obj)) {
1523 size = PyUnicode_GET_SIZE(obj);
1524 if (size == 1) {
1525 ord = (long)*PyUnicode_AS_UNICODE(obj);
1526 return PyInt_FromLong(ord);
1527 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001528#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001529 } else {
1530 PyErr_Format(PyExc_TypeError,
1531 "ord() expected string of length 1, but " \
1532 "%.200s found", obj->ob_type->tp_name);
1533 return NULL;
1534 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001535
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001536 PyErr_Format(PyExc_TypeError,
1537 "ord() expected a character, "
1538 "but string of length %zd found",
1539 size);
1540 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001541}
1542
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001543PyDoc_STRVAR(ord_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001544"ord(c) -> integer\n\
1545\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001546Return the integer ordinal of a one-character string.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001547
1548
Guido van Rossum79f25d91997-04-29 20:08:16 +00001549static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001550builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001551{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001552 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001553
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001554 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1555 return NULL;
1556 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001557}
1558
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001559PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001560"pow(x, y[, z]) -> number\n\
1561\n\
1562With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001563equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001564
1565
Eric Smith7c478942008-03-18 23:45:49 +00001566static PyObject *
1567builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1568{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001569 static char *kwlist[] = {"sep", "end", "file", 0};
1570 static PyObject *dummy_args = NULL;
1571 static PyObject *unicode_newline = NULL, *unicode_space = NULL;
1572 static PyObject *str_newline = NULL, *str_space = NULL;
1573 PyObject *newline, *space;
1574 PyObject *sep = NULL, *end = NULL, *file = NULL;
1575 int i, err, use_unicode = 0;
Eric Smith7c478942008-03-18 23:45:49 +00001576
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001577 if (dummy_args == NULL) {
1578 if (!(dummy_args = PyTuple_New(0)))
1579 return NULL;
1580 }
1581 if (str_newline == NULL) {
1582 str_newline = PyString_FromString("\n");
1583 if (str_newline == NULL)
1584 return NULL;
1585 str_space = PyString_FromString(" ");
1586 if (str_space == NULL) {
1587 Py_CLEAR(str_newline);
1588 return NULL;
1589 }
Martin v. Löwised11a5d2012-05-20 10:42:17 +02001590#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001591 unicode_newline = PyUnicode_FromString("\n");
1592 if (unicode_newline == NULL) {
1593 Py_CLEAR(str_newline);
1594 Py_CLEAR(str_space);
1595 return NULL;
1596 }
1597 unicode_space = PyUnicode_FromString(" ");
1598 if (unicode_space == NULL) {
1599 Py_CLEAR(str_newline);
1600 Py_CLEAR(str_space);
1601 Py_CLEAR(unicode_space);
1602 return NULL;
1603 }
Martin v. Löwised11a5d2012-05-20 10:42:17 +02001604#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001605 }
1606 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1607 kwlist, &sep, &end, &file))
1608 return NULL;
1609 if (file == NULL || file == Py_None) {
1610 file = PySys_GetObject("stdout");
1611 /* sys.stdout may be None when FILE* stdout isn't connected */
1612 if (file == Py_None)
1613 Py_RETURN_NONE;
1614 }
1615 if (sep == Py_None) {
1616 sep = NULL;
1617 }
1618 else if (sep) {
1619 if (PyUnicode_Check(sep)) {
1620 use_unicode = 1;
1621 }
1622 else if (!PyString_Check(sep)) {
1623 PyErr_Format(PyExc_TypeError,
1624 "sep must be None, str or unicode, not %.200s",
1625 sep->ob_type->tp_name);
1626 return NULL;
1627 }
1628 }
1629 if (end == Py_None)
1630 end = NULL;
1631 else if (end) {
1632 if (PyUnicode_Check(end)) {
1633 use_unicode = 1;
1634 }
1635 else if (!PyString_Check(end)) {
1636 PyErr_Format(PyExc_TypeError,
1637 "end must be None, str or unicode, not %.200s",
1638 end->ob_type->tp_name);
1639 return NULL;
1640 }
1641 }
Benjamin Peterson753d1622009-07-02 18:16:45 +00001642
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001643 if (!use_unicode) {
1644 for (i = 0; i < PyTuple_Size(args); i++) {
1645 if (PyUnicode_Check(PyTuple_GET_ITEM(args, i))) {
1646 use_unicode = 1;
1647 break;
1648 }
1649 }
1650 }
1651 if (use_unicode) {
1652 newline = unicode_newline;
1653 space = unicode_space;
1654 }
1655 else {
1656 newline = str_newline;
1657 space = str_space;
1658 }
Eric Smith7c478942008-03-18 23:45:49 +00001659
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001660 for (i = 0; i < PyTuple_Size(args); i++) {
1661 if (i > 0) {
1662 if (sep == NULL)
1663 err = PyFile_WriteObject(space, file,
1664 Py_PRINT_RAW);
1665 else
1666 err = PyFile_WriteObject(sep, file,
1667 Py_PRINT_RAW);
1668 if (err)
1669 return NULL;
1670 }
1671 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1672 Py_PRINT_RAW);
1673 if (err)
1674 return NULL;
1675 }
Eric Smith7c478942008-03-18 23:45:49 +00001676
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001677 if (end == NULL)
1678 err = PyFile_WriteObject(newline, file, Py_PRINT_RAW);
1679 else
1680 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1681 if (err)
1682 return NULL;
Eric Smith7c478942008-03-18 23:45:49 +00001683
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001684 Py_RETURN_NONE;
Eric Smith7c478942008-03-18 23:45:49 +00001685}
1686
1687PyDoc_STRVAR(print_doc,
1688"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
1689\n\
1690Prints the values to a stream, or to sys.stdout by default.\n\
1691Optional keyword arguments:\n\
1692file: a file-like object (stream); defaults to the current sys.stdout.\n\
1693sep: string inserted between values, default a space.\n\
1694end: string appended after the last value, default a newline.");
1695
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001696
1697/* Return number of items in range (lo, hi, step), when arguments are
1698 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1699 * & only if the true value is too large to fit in a signed long.
1700 * Arguments MUST return 1 with either PyInt_Check() or
1701 * PyLong_Check(). Return -1 when there is an error.
1702 */
1703static long
1704get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
1705{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001706 /* -------------------------------------------------------------
1707 Algorithm is equal to that of get_len_of_range(), but it operates
1708 on PyObjects (which are assumed to be PyLong or PyInt objects).
1709 ---------------------------------------------------------------*/
1710 long n;
1711 PyObject *diff = NULL;
1712 PyObject *one = NULL;
1713 PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
1714 /* holds sub-expression evaluations */
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001715
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001716 /* if (lo >= hi), return length of 0. */
1717 if (PyObject_Compare(lo, hi) >= 0)
1718 return 0;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001719
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001720 if ((one = PyLong_FromLong(1L)) == NULL)
1721 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001722
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001723 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
1724 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001725
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001726 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
1727 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001728
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001729 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
1730 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001731
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001732 if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
1733 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001734
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001735 n = PyLong_AsLong(tmp3);
1736 if (PyErr_Occurred()) { /* Check for Overflow */
1737 PyErr_Clear();
1738 goto Fail;
1739 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001740
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001741 Py_DECREF(tmp3);
1742 Py_DECREF(tmp2);
1743 Py_DECREF(diff);
1744 Py_DECREF(tmp1);
1745 Py_DECREF(one);
1746 return n;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001747
1748 Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001749 Py_XDECREF(tmp3);
1750 Py_XDECREF(tmp2);
1751 Py_XDECREF(diff);
1752 Py_XDECREF(tmp1);
1753 Py_XDECREF(one);
1754 return -1;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001755}
1756
Mark Dickinsona8d26682010-05-04 16:18:25 +00001757/* Helper function for handle_range_longs. If arg is int or long
1758 object, returns it with incremented reference count. If arg is
1759 float, raises type error. As a last resort, creates a new int by
1760 calling arg type's nb_int method if it is defined. Returns NULL
1761 and sets exception on error.
1762
1763 Returns a new reference to an int object. */
1764static PyObject *
1765get_range_long_argument(PyObject *arg, const char *name)
1766{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001767 PyObject *v;
1768 PyNumberMethods *nb;
1769 if (PyInt_Check(arg) || PyLong_Check(arg)) {
1770 Py_INCREF(arg);
1771 return arg;
1772 }
1773 if (PyFloat_Check(arg) ||
1774 (nb = Py_TYPE(arg)->tp_as_number) == NULL ||
1775 nb->nb_int == NULL) {
1776 PyErr_Format(PyExc_TypeError,
1777 "range() integer %s argument expected, got %s.",
1778 name, arg->ob_type->tp_name);
1779 return NULL;
1780 }
1781 v = nb->nb_int(arg);
1782 if (v == NULL)
1783 return NULL;
1784 if (PyInt_Check(v) || PyLong_Check(v))
1785 return v;
1786 Py_DECREF(v);
1787 PyErr_SetString(PyExc_TypeError,
1788 "__int__ should return int object");
1789 return NULL;
Mark Dickinsona8d26682010-05-04 16:18:25 +00001790}
1791
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001792/* An extension of builtin_range() that handles the case when PyLong
1793 * arguments are given. */
1794static PyObject *
Mark Dickinsonef9b4ab2010-05-04 16:19:06 +00001795handle_range_longs(PyObject *self, PyObject *args)
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001796{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001797 PyObject *ilow = NULL;
1798 PyObject *ihigh = NULL;
1799 PyObject *istep = NULL;
Tim Peters874e1f72003-04-13 22:13:08 +00001800
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001801 PyObject *low = NULL;
1802 PyObject *high = NULL;
1803 PyObject *step = NULL;
Mark Dickinsona8d26682010-05-04 16:18:25 +00001804
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001805 PyObject *curnum = NULL;
1806 PyObject *v = NULL;
1807 long bign;
1808 Py_ssize_t i, n;
1809 int cmp_result;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001810
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001811 PyObject *zero = PyLong_FromLong(0);
Tim Peters874e1f72003-04-13 22:13:08 +00001812
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001813 if (zero == NULL)
1814 return NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001815
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001816 if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
1817 Py_DECREF(zero);
1818 return NULL;
1819 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001820
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001821 /* Figure out which way we were called, supply defaults, and be
1822 * sure to incref everything so that the decrefs at the end
1823 * are correct. NB: ilow, ihigh and istep are borrowed references.
1824 */
1825 assert(ilow != NULL);
1826 if (ihigh == NULL) {
1827 /* only 1 arg -- it's the upper limit */
1828 ihigh = ilow;
1829 ilow = NULL;
1830 }
Mark Dickinsona8d26682010-05-04 16:18:25 +00001831
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001832 /* convert ihigh if necessary */
1833 assert(ihigh != NULL);
1834 high = get_range_long_argument(ihigh, "end");
1835 if (high == NULL)
1836 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001837
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001838 /* ihigh correct now; do ilow */
1839 if (ilow == NULL) {
1840 Py_INCREF(zero);
1841 low = zero;
1842 }
1843 else {
1844 low = get_range_long_argument(ilow, "start");
1845 if (low == NULL)
1846 goto Fail;
1847 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001848
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001849 /* ilow and ihigh correct now; do istep */
1850 if (istep == NULL)
1851 step = PyLong_FromLong(1);
1852 else
1853 step = get_range_long_argument(istep, "step");
1854 if (step == NULL)
1855 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001856
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001857 if (PyObject_Cmp(step, zero, &cmp_result) == -1)
1858 goto Fail;
Tim Peters874e1f72003-04-13 22:13:08 +00001859
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001860 if (cmp_result == 0) {
1861 PyErr_SetString(PyExc_ValueError,
1862 "range() step argument must not be zero");
1863 goto Fail;
1864 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001865
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001866 if (cmp_result > 0)
1867 bign = get_len_of_range_longs(low, high, step);
1868 else {
1869 PyObject *neg_step = PyNumber_Negative(step);
1870 if (neg_step == NULL)
1871 goto Fail;
1872 bign = get_len_of_range_longs(high, low, neg_step);
1873 Py_DECREF(neg_step);
1874 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001875
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001876 n = (Py_ssize_t)bign;
1877 if (bign < 0 || (long)n != bign) {
1878 PyErr_SetString(PyExc_OverflowError,
1879 "range() result has too many items");
1880 goto Fail;
1881 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001882
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001883 v = PyList_New(n);
1884 if (v == NULL)
1885 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001886
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001887 curnum = low;
1888 Py_INCREF(curnum);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001889
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001890 for (i = 0; i < n; i++) {
1891 PyObject *w = PyNumber_Long(curnum);
1892 PyObject *tmp_num;
1893 if (w == NULL)
1894 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001895
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001896 PyList_SET_ITEM(v, i, w);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001897
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001898 tmp_num = PyNumber_Add(curnum, step);
1899 if (tmp_num == NULL)
1900 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001901
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001902 Py_DECREF(curnum);
1903 curnum = tmp_num;
1904 }
1905 Py_DECREF(low);
1906 Py_DECREF(high);
1907 Py_DECREF(step);
1908 Py_DECREF(zero);
1909 Py_DECREF(curnum);
1910 return v;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001911
1912 Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001913 Py_XDECREF(low);
1914 Py_XDECREF(high);
1915 Py_XDECREF(step);
1916 Py_DECREF(zero);
1917 Py_XDECREF(curnum);
1918 Py_XDECREF(v);
1919 return NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001920}
1921
Guido van Rossum124eff01999-02-23 16:11:01 +00001922/* Return number of items in range/xrange (lo, hi, step). step > 0
1923 * required. Return a value < 0 if & only if the true value is too
1924 * large to fit in a signed long.
1925 */
1926static long
Thomas Wouterse28c2962000-07-23 22:21:32 +00001927get_len_of_range(long lo, long hi, long step)
Guido van Rossum124eff01999-02-23 16:11:01 +00001928{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001929 /* -------------------------------------------------------------
1930 If lo >= hi, the range is empty.
1931 Else if n values are in the range, the last one is
1932 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1933 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1934 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1935 the RHS is non-negative and so truncation is the same as the
1936 floor. Letting M be the largest positive long, the worst case
1937 for the RHS numerator is hi=M, lo=-M-1, and then
1938 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1939 precision to compute the RHS exactly.
1940 ---------------------------------------------------------------*/
1941 long n = 0;
1942 if (lo < hi) {
1943 unsigned long uhi = (unsigned long)hi;
1944 unsigned long ulo = (unsigned long)lo;
1945 unsigned long diff = uhi - ulo - 1;
1946 n = (long)(diff / (unsigned long)step + 1);
1947 }
1948 return n;
Guido van Rossum124eff01999-02-23 16:11:01 +00001949}
1950
Guido van Rossum79f25d91997-04-29 20:08:16 +00001951static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001952builtin_range(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001953{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001954 long ilow = 0, ihigh = 0, istep = 1;
1955 long bign;
1956 Py_ssize_t i, n;
Guido van Rossum124eff01999-02-23 16:11:01 +00001957
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001958 PyObject *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001959
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001960 if (PyTuple_Size(args) <= 1) {
1961 if (!PyArg_ParseTuple(args,
1962 "l;range() requires 1-3 int arguments",
1963 &ihigh)) {
1964 PyErr_Clear();
1965 return handle_range_longs(self, args);
1966 }
1967 }
1968 else {
1969 if (!PyArg_ParseTuple(args,
1970 "ll|l;range() requires 1-3 int arguments",
1971 &ilow, &ihigh, &istep)) {
1972 PyErr_Clear();
1973 return handle_range_longs(self, args);
1974 }
1975 }
1976 if (istep == 0) {
1977 PyErr_SetString(PyExc_ValueError,
1978 "range() step argument must not be zero");
1979 return NULL;
1980 }
1981 if (istep > 0)
1982 bign = get_len_of_range(ilow, ihigh, istep);
1983 else
1984 bign = get_len_of_range(ihigh, ilow, -istep);
1985 n = (Py_ssize_t)bign;
1986 if (bign < 0 || (long)n != bign) {
1987 PyErr_SetString(PyExc_OverflowError,
1988 "range() result has too many items");
1989 return NULL;
1990 }
1991 v = PyList_New(n);
1992 if (v == NULL)
1993 return NULL;
1994 for (i = 0; i < n; i++) {
1995 PyObject *w = PyInt_FromLong(ilow);
1996 if (w == NULL) {
1997 Py_DECREF(v);
1998 return NULL;
1999 }
2000 PyList_SET_ITEM(v, i, w);
2001 ilow += istep;
2002 }
2003 return v;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002004}
2005
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002006PyDoc_STRVAR(range_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002007"range([start,] stop[, step]) -> list of integers\n\
2008\n\
2009Return a list containing an arithmetic progression of integers.\n\
2010range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
2011When step is given, it specifies the increment (or decrement).\n\
2012For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002013These are exactly the valid indices for a list of 4 elements.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002014
2015
Guido van Rossum79f25d91997-04-29 20:08:16 +00002016static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002017builtin_raw_input(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002018{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002019 PyObject *v = NULL;
2020 PyObject *fin = PySys_GetObject("stdin");
2021 PyObject *fout = PySys_GetObject("stdout");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002022
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002023 if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
2024 return NULL;
Martin v. Löwis31d2df52002-08-14 15:46:02 +00002025
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002026 if (fin == NULL) {
2027 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
2028 return NULL;
2029 }
2030 if (fout == NULL) {
2031 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
2032 return NULL;
2033 }
2034 if (PyFile_SoftSpace(fout, 0)) {
2035 if (PyFile_WriteString(" ", fout) != 0)
2036 return NULL;
2037 }
2038 if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
2039 && isatty(fileno(PyFile_AsFile(fin)))
2040 && isatty(fileno(PyFile_AsFile(fout)))) {
2041 PyObject *po;
2042 char *prompt;
2043 char *s;
2044 PyObject *result;
2045 if (v != NULL) {
2046 po = PyObject_Str(v);
2047 if (po == NULL)
2048 return NULL;
2049 prompt = PyString_AsString(po);
2050 if (prompt == NULL)
2051 return NULL;
2052 }
2053 else {
2054 po = NULL;
2055 prompt = "";
2056 }
2057 s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
2058 prompt);
2059 Py_XDECREF(po);
2060 if (s == NULL) {
2061 if (!PyErr_Occurred())
2062 PyErr_SetNone(PyExc_KeyboardInterrupt);
2063 return NULL;
2064 }
2065 if (*s == '\0') {
2066 PyErr_SetNone(PyExc_EOFError);
2067 result = NULL;
2068 }
2069 else { /* strip trailing '\n' */
2070 size_t len = strlen(s);
2071 if (len > PY_SSIZE_T_MAX) {
2072 PyErr_SetString(PyExc_OverflowError,
2073 "[raw_]input: input too long");
2074 result = NULL;
2075 }
2076 else {
2077 result = PyString_FromStringAndSize(s, len-1);
2078 }
2079 }
2080 PyMem_FREE(s);
2081 return result;
2082 }
2083 if (v != NULL) {
2084 if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
2085 return NULL;
2086 }
2087 return PyFile_GetLine(fin, -1);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002088}
2089
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002090PyDoc_STRVAR(raw_input_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002091"raw_input([prompt]) -> string\n\
2092\n\
2093Read a string from standard input. The trailing newline is stripped.\n\
2094If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
2095On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002096is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002097
2098
Guido van Rossum79f25d91997-04-29 20:08:16 +00002099static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002100builtin_reduce(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002101{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002102 static PyObject *functools_reduce = NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002103
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002104 if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
2105 "use functools.reduce()", 1) < 0)
2106 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +00002107
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002108 if (functools_reduce == NULL) {
2109 PyObject *functools = PyImport_ImportModule("functools");
2110 if (functools == NULL)
2111 return NULL;
2112 functools_reduce = PyObject_GetAttrString(functools, "reduce");
2113 Py_DECREF(functools);
2114 if (functools_reduce == NULL)
2115 return NULL;
2116 }
2117 return PyObject_Call(functools_reduce, args, NULL);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002118}
2119
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002120PyDoc_STRVAR(reduce_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002121"reduce(function, sequence[, initial]) -> value\n\
2122\n\
2123Apply a function of two arguments cumulatively to the items of a sequence,\n\
2124from left to right, so as to reduce the sequence to a single value.\n\
2125For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
2126((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
2127of the sequence in the calculation, and serves as a default when the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002128sequence is empty.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002129
2130
Guido van Rossum79f25d91997-04-29 20:08:16 +00002131static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002132builtin_reload(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002133{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002134 if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
2135 1) < 0)
2136 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +00002137
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002138 return PyImport_ReloadModule(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002139}
2140
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002141PyDoc_STRVAR(reload_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002142"reload(module) -> module\n\
2143\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002144Reload the module. The module must have been successfully imported before.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002145
2146
Guido van Rossum79f25d91997-04-29 20:08:16 +00002147static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002148builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00002149{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002150 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002151}
2152
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002153PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002154"repr(object) -> string\n\
2155\n\
2156Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002157For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002158
2159
Guido van Rossum79f25d91997-04-29 20:08:16 +00002160static PyObject *
Georg Brandlccadf842006-03-31 18:54:53 +00002161builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002162{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002163 double x;
2164 PyObject *o_ndigits = NULL;
2165 Py_ssize_t ndigits;
2166 static char *kwlist[] = {"number", "ndigits", 0};
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002167
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002168 if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|O:round",
2169 kwlist, &x, &o_ndigits))
2170 return NULL;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002171
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002172 if (o_ndigits == NULL) {
2173 /* second argument defaults to 0 */
2174 ndigits = 0;
2175 }
2176 else {
2177 /* interpret 2nd argument as a Py_ssize_t; clip on overflow */
2178 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
2179 if (ndigits == -1 && PyErr_Occurred())
2180 return NULL;
2181 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002182
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002183 /* nans, infinities and zeros round to themselves */
2184 if (!Py_IS_FINITE(x) || x == 0.0)
2185 return PyFloat_FromDouble(x);
Mark Dickinsonbce78372009-11-24 10:54:58 +00002186
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002187 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
2188 always rounds to itself. For ndigits < NDIGITS_MIN, x always
2189 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002190#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
2191#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002192 if (ndigits > NDIGITS_MAX)
2193 /* return x */
2194 return PyFloat_FromDouble(x);
2195 else if (ndigits < NDIGITS_MIN)
2196 /* return 0.0, but with sign of x */
2197 return PyFloat_FromDouble(0.0*x);
2198 else
2199 /* finite x, and ndigits is not unreasonably large */
2200 /* _Py_double_round is defined in floatobject.c */
2201 return _Py_double_round(x, (int)ndigits);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002202#undef NDIGITS_MAX
2203#undef NDIGITS_MIN
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002204}
2205
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002206PyDoc_STRVAR(round_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002207"round(number[, ndigits]) -> floating point number\n\
2208\n\
2209Round a number to a given precision in decimal digits (default 0 digits).\n\
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +00002210This always returns a floating point number. Precision may be negative.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002211
Raymond Hettinger64958a12003-12-17 20:43:33 +00002212static PyObject *
2213builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2214{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002215 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
2216 PyObject *callable;
2217 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
2218 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002219
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002220 /* args 1-4 should match listsort in Objects/listobject.c */
2221 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
2222 kwlist, &seq, &compare, &keyfunc, &reverse))
2223 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002224
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002225 newlist = PySequence_List(seq);
2226 if (newlist == NULL)
2227 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002228
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002229 callable = PyObject_GetAttrString(newlist, "sort");
2230 if (callable == NULL) {
2231 Py_DECREF(newlist);
2232 return NULL;
2233 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002234
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002235 newargs = PyTuple_GetSlice(args, 1, 4);
2236 if (newargs == NULL) {
2237 Py_DECREF(newlist);
2238 Py_DECREF(callable);
2239 return NULL;
2240 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00002241
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002242 v = PyObject_Call(callable, newargs, kwds);
2243 Py_DECREF(newargs);
2244 Py_DECREF(callable);
2245 if (v == NULL) {
2246 Py_DECREF(newlist);
2247 return NULL;
2248 }
2249 Py_DECREF(v);
2250 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002251}
2252
2253PyDoc_STRVAR(sorted_doc,
2254"sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002255
Guido van Rossum79f25d91997-04-29 20:08:16 +00002256static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002257builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002258{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002259 PyObject *v = NULL;
2260 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002261
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002262 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2263 return NULL;
2264 if (v == NULL) {
2265 d = PyEval_GetLocals();
2266 if (d == NULL) {
2267 if (!PyErr_Occurred())
2268 PyErr_SetString(PyExc_SystemError,
2269 "vars(): no locals!?");
2270 }
2271 else
2272 Py_INCREF(d);
2273 }
2274 else {
2275 d = PyObject_GetAttrString(v, "__dict__");
2276 if (d == NULL) {
2277 PyErr_SetString(PyExc_TypeError,
2278 "vars() argument must have __dict__ attribute");
2279 return NULL;
2280 }
2281 }
2282 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002283}
2284
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002285PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002286"vars([object]) -> dictionary\n\
2287\n\
2288Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002289With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002290
Alex Martellia70b1912003-04-22 08:12:33 +00002291
2292static PyObject*
2293builtin_sum(PyObject *self, PyObject *args)
2294{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002295 PyObject *seq;
2296 PyObject *result = NULL;
2297 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002298
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002299 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
2300 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002301
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002302 iter = PyObject_GetIter(seq);
2303 if (iter == NULL)
2304 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002305
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002306 if (result == NULL) {
2307 result = PyInt_FromLong(0);
2308 if (result == NULL) {
2309 Py_DECREF(iter);
2310 return NULL;
2311 }
2312 } else {
2313 /* reject string values for 'start' parameter */
2314 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
2315 PyErr_SetString(PyExc_TypeError,
2316 "sum() can't sum strings [use ''.join(seq) instead]");
2317 Py_DECREF(iter);
2318 return NULL;
2319 }
2320 Py_INCREF(result);
2321 }
Alex Martellia70b1912003-04-22 08:12:33 +00002322
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002323#ifndef SLOW_SUM
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002324 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2325 Assumes all inputs are the same type. If the assumption fails, default
2326 to the more general routine.
2327 */
2328 if (PyInt_CheckExact(result)) {
2329 long i_result = PyInt_AS_LONG(result);
2330 Py_DECREF(result);
2331 result = NULL;
2332 while(result == NULL) {
2333 item = PyIter_Next(iter);
2334 if (item == NULL) {
2335 Py_DECREF(iter);
2336 if (PyErr_Occurred())
2337 return NULL;
2338 return PyInt_FromLong(i_result);
2339 }
2340 if (PyInt_CheckExact(item)) {
2341 long b = PyInt_AS_LONG(item);
2342 long x = i_result + b;
2343 if ((x^i_result) >= 0 || (x^b) >= 0) {
2344 i_result = x;
2345 Py_DECREF(item);
2346 continue;
2347 }
2348 }
2349 /* Either overflowed or is not an int. Restore real objects and process normally */
2350 result = PyInt_FromLong(i_result);
2351 temp = PyNumber_Add(result, item);
2352 Py_DECREF(result);
2353 Py_DECREF(item);
2354 result = temp;
2355 if (result == NULL) {
2356 Py_DECREF(iter);
2357 return NULL;
2358 }
2359 }
2360 }
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002361
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002362 if (PyFloat_CheckExact(result)) {
2363 double f_result = PyFloat_AS_DOUBLE(result);
2364 Py_DECREF(result);
2365 result = NULL;
2366 while(result == NULL) {
2367 item = PyIter_Next(iter);
2368 if (item == NULL) {
2369 Py_DECREF(iter);
2370 if (PyErr_Occurred())
2371 return NULL;
2372 return PyFloat_FromDouble(f_result);
2373 }
2374 if (PyFloat_CheckExact(item)) {
2375 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2376 f_result += PyFloat_AS_DOUBLE(item);
2377 PyFPE_END_PROTECT(f_result)
2378 Py_DECREF(item);
2379 continue;
2380 }
2381 if (PyInt_CheckExact(item)) {
2382 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2383 f_result += (double)PyInt_AS_LONG(item);
2384 PyFPE_END_PROTECT(f_result)
2385 Py_DECREF(item);
2386 continue;
2387 }
2388 result = PyFloat_FromDouble(f_result);
2389 temp = PyNumber_Add(result, item);
2390 Py_DECREF(result);
2391 Py_DECREF(item);
2392 result = temp;
2393 if (result == NULL) {
2394 Py_DECREF(iter);
2395 return NULL;
2396 }
2397 }
2398 }
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002399#endif
2400
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002401 for(;;) {
2402 item = PyIter_Next(iter);
2403 if (item == NULL) {
2404 /* error, or end-of-sequence */
2405 if (PyErr_Occurred()) {
2406 Py_DECREF(result);
2407 result = NULL;
2408 }
2409 break;
2410 }
2411 /* It's tempting to use PyNumber_InPlaceAdd instead of
2412 PyNumber_Add here, to avoid quadratic running time
2413 when doing 'sum(list_of_lists, [])'. However, this
2414 would produce a change in behaviour: a snippet like
Mark Dickinson0e0e2152009-10-26 14:18:44 +00002415
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002416 empty = []
2417 sum([[x] for x in range(10)], empty)
Mark Dickinson0e0e2152009-10-26 14:18:44 +00002418
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002419 would change the value of empty. */
2420 temp = PyNumber_Add(result, item);
2421 Py_DECREF(result);
2422 Py_DECREF(item);
2423 result = temp;
2424 if (result == NULL)
2425 break;
2426 }
2427 Py_DECREF(iter);
2428 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002429}
2430
2431PyDoc_STRVAR(sum_doc,
Georg Brandl8134d062006-10-12 12:33:07 +00002432"sum(sequence[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002433\n\
2434Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
Georg Brandl8134d062006-10-12 12:33:07 +00002435of parameter 'start' (which defaults to 0). When the sequence is\n\
2436empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002437
2438
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002439static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002440builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002441{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002442 PyObject *inst;
2443 PyObject *cls;
2444 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002445
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002446 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2447 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002448
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002449 retval = PyObject_IsInstance(inst, cls);
2450 if (retval < 0)
2451 return NULL;
2452 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002453}
2454
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002455PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002456"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002457\n\
2458Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002459With a type as second argument, return whether that is the object's type.\n\
2460The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002461isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002462
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002463
2464static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002465builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002466{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002467 PyObject *derived;
2468 PyObject *cls;
2469 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002470
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002471 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2472 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002473
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002474 retval = PyObject_IsSubclass(derived, cls);
2475 if (retval < 0)
2476 return NULL;
2477 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002478}
2479
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002480PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002481"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002482\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002483Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2484When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2485is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002486
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002487
Barry Warsawbd599b52000-08-03 15:45:29 +00002488static PyObject*
2489builtin_zip(PyObject *self, PyObject *args)
2490{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002491 PyObject *ret;
2492 const Py_ssize_t itemsize = PySequence_Length(args);
2493 Py_ssize_t i;
2494 PyObject *itlist; /* tuple of iterators */
2495 Py_ssize_t len; /* guess at result length */
Barry Warsawbd599b52000-08-03 15:45:29 +00002496
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002497 if (itemsize == 0)
2498 return PyList_New(0);
Raymond Hettingereaef6152003-08-02 07:42:57 +00002499
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002500 /* args must be a tuple */
2501 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002502
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002503 /* Guess at result length: the shortest of the input lengths.
2504 If some argument refuses to say, we refuse to guess too, lest
2505 an argument like xrange(sys.maxint) lead us astray.*/
2506 len = -1; /* unknown */
2507 for (i = 0; i < itemsize; ++i) {
2508 PyObject *item = PyTuple_GET_ITEM(args, i);
2509 Py_ssize_t thislen = _PyObject_LengthHint(item, -2);
2510 if (thislen < 0) {
2511 if (thislen == -1)
2512 return NULL;
2513 len = -1;
2514 break;
2515 }
2516 else if (len < 0 || thislen < len)
2517 len = thislen;
2518 }
Tim Peters67d687a2002-04-29 21:27:32 +00002519
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002520 /* allocate result list */
2521 if (len < 0)
2522 len = 10; /* arbitrary */
2523 if ((ret = PyList_New(len)) == NULL)
2524 return NULL;
Barry Warsawbd599b52000-08-03 15:45:29 +00002525
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002526 /* obtain iterators */
2527 itlist = PyTuple_New(itemsize);
2528 if (itlist == NULL)
2529 goto Fail_ret;
2530 for (i = 0; i < itemsize; ++i) {
2531 PyObject *item = PyTuple_GET_ITEM(args, i);
2532 PyObject *it = PyObject_GetIter(item);
2533 if (it == NULL) {
2534 if (PyErr_ExceptionMatches(PyExc_TypeError))
2535 PyErr_Format(PyExc_TypeError,
2536 "zip argument #%zd must support iteration",
2537 i+1);
2538 goto Fail_ret_itlist;
2539 }
2540 PyTuple_SET_ITEM(itlist, i, it);
2541 }
Barry Warsawbd599b52000-08-03 15:45:29 +00002542
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002543 /* build result into ret list */
2544 for (i = 0; ; ++i) {
2545 int j;
2546 PyObject *next = PyTuple_New(itemsize);
2547 if (!next)
2548 goto Fail_ret_itlist;
Tim Peters8572b4f2001-05-06 01:05:02 +00002549
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002550 for (j = 0; j < itemsize; j++) {
2551 PyObject *it = PyTuple_GET_ITEM(itlist, j);
2552 PyObject *item = PyIter_Next(it);
2553 if (!item) {
2554 if (PyErr_Occurred()) {
2555 Py_DECREF(ret);
2556 ret = NULL;
2557 }
2558 Py_DECREF(next);
2559 Py_DECREF(itlist);
2560 goto Done;
2561 }
2562 PyTuple_SET_ITEM(next, j, item);
2563 }
Tim Peters8572b4f2001-05-06 01:05:02 +00002564
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002565 if (i < len)
2566 PyList_SET_ITEM(ret, i, next);
2567 else {
2568 int status = PyList_Append(ret, next);
2569 Py_DECREF(next);
2570 ++len;
2571 if (status < 0)
2572 goto Fail_ret_itlist;
2573 }
2574 }
Tim Peters8572b4f2001-05-06 01:05:02 +00002575
Tim Peters67d687a2002-04-29 21:27:32 +00002576Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002577 if (ret != NULL && i < len) {
2578 /* The list is too big. */
2579 if (PyList_SetSlice(ret, i, len, NULL) < 0)
2580 return NULL;
2581 }
2582 return ret;
Tim Peters67d687a2002-04-29 21:27:32 +00002583
Tim Peters8572b4f2001-05-06 01:05:02 +00002584Fail_ret_itlist:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002585 Py_DECREF(itlist);
Tim Peters8572b4f2001-05-06 01:05:02 +00002586Fail_ret:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002587 Py_DECREF(ret);
2588 return NULL;
Barry Warsawbd599b52000-08-03 15:45:29 +00002589}
2590
2591
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002592PyDoc_STRVAR(zip_doc,
Barry Warsawbd599b52000-08-03 15:45:29 +00002593"zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2594\n\
2595Return a list of tuples, where each tuple contains the i-th element\n\
2596from each of the argument sequences. The returned list is truncated\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002597in length to the length of the shortest argument sequence.");
Barry Warsawbd599b52000-08-03 15:45:29 +00002598
2599
Guido van Rossum79f25d91997-04-29 20:08:16 +00002600static PyMethodDef builtin_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002601 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2602 {"abs", builtin_abs, METH_O, abs_doc},
2603 {"all", builtin_all, METH_O, all_doc},
2604 {"any", builtin_any, METH_O, any_doc},
2605 {"apply", builtin_apply, METH_VARARGS, apply_doc},
2606 {"bin", builtin_bin, METH_O, bin_doc},
2607 {"callable", builtin_callable, METH_O, callable_doc},
2608 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2609 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
2610 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
2611 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2612 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2613 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2614 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2615 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2616 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
2617 {"filter", builtin_filter, METH_VARARGS, filter_doc},
2618 {"format", builtin_format, METH_VARARGS, format_doc},
2619 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2620 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2621 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2622 {"hash", builtin_hash, METH_O, hash_doc},
2623 {"hex", builtin_hex, METH_O, hex_doc},
2624 {"id", builtin_id, METH_O, id_doc},
2625 {"input", builtin_input, METH_VARARGS, input_doc},
2626 {"intern", builtin_intern, METH_VARARGS, intern_doc},
2627 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2628 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2629 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2630 {"len", builtin_len, METH_O, len_doc},
2631 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2632 {"map", builtin_map, METH_VARARGS, map_doc},
2633 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2634 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2635 {"next", builtin_next, METH_VARARGS, next_doc},
2636 {"oct", builtin_oct, METH_O, oct_doc},
2637 {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
2638 {"ord", builtin_ord, METH_O, ord_doc},
2639 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2640 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2641 {"range", builtin_range, METH_VARARGS, range_doc},
2642 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
2643 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
2644 {"reload", builtin_reload, METH_O, reload_doc},
2645 {"repr", builtin_repr, METH_O, repr_doc},
2646 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2647 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2648 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2649 {"sum", builtin_sum, METH_VARARGS, sum_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002650#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002651 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002652#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002653 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2654 {"zip", builtin_zip, METH_VARARGS, zip_doc},
2655 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002656};
2657
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002658PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002659"Built-in functions, exceptions, and other objects.\n\
2660\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002661Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002662
Guido van Rossum25ce5661997-08-02 03:10:38 +00002663PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002664_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002665{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002666 PyObject *mod, *dict, *debug;
2667 mod = Py_InitModule4("__builtin__", builtin_methods,
2668 builtin_doc, (PyObject *)NULL,
2669 PYTHON_API_VERSION);
2670 if (mod == NULL)
2671 return NULL;
2672 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002673
Tim Peters7571a0f2003-03-23 17:52:28 +00002674#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002675 /* __builtin__ exposes a number of statically allocated objects
2676 * that, before this code was added in 2.3, never showed up in
2677 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2678 * result, programs leaking references to None and False (etc)
2679 * couldn't be diagnosed by examining sys.getobjects(0).
2680 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002681#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2682#else
2683#define ADD_TO_ALL(OBJECT) (void)0
2684#endif
2685
Tim Peters4b7625e2001-09-13 21:37:17 +00002686#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002687 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2688 return NULL; \
2689 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002690
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002691 SETBUILTIN("None", Py_None);
2692 SETBUILTIN("Ellipsis", Py_Ellipsis);
2693 SETBUILTIN("NotImplemented", Py_NotImplemented);
2694 SETBUILTIN("False", Py_False);
2695 SETBUILTIN("True", Py_True);
2696 SETBUILTIN("basestring", &PyBaseString_Type);
2697 SETBUILTIN("bool", &PyBool_Type);
2698 SETBUILTIN("memoryview", &PyMemoryView_Type);
2699 SETBUILTIN("bytearray", &PyByteArray_Type);
2700 SETBUILTIN("bytes", &PyString_Type);
2701 SETBUILTIN("buffer", &PyBuffer_Type);
2702 SETBUILTIN("classmethod", &PyClassMethod_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002703#ifndef WITHOUT_COMPLEX
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002704 SETBUILTIN("complex", &PyComplex_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002705#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002706 SETBUILTIN("dict", &PyDict_Type);
2707 SETBUILTIN("enumerate", &PyEnum_Type);
2708 SETBUILTIN("file", &PyFile_Type);
2709 SETBUILTIN("float", &PyFloat_Type);
2710 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2711 SETBUILTIN("property", &PyProperty_Type);
2712 SETBUILTIN("int", &PyInt_Type);
2713 SETBUILTIN("list", &PyList_Type);
2714 SETBUILTIN("long", &PyLong_Type);
2715 SETBUILTIN("object", &PyBaseObject_Type);
2716 SETBUILTIN("reversed", &PyReversed_Type);
2717 SETBUILTIN("set", &PySet_Type);
2718 SETBUILTIN("slice", &PySlice_Type);
2719 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2720 SETBUILTIN("str", &PyString_Type);
2721 SETBUILTIN("super", &PySuper_Type);
2722 SETBUILTIN("tuple", &PyTuple_Type);
2723 SETBUILTIN("type", &PyType_Type);
2724 SETBUILTIN("xrange", &PyRange_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002725#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002726 SETBUILTIN("unicode", &PyUnicode_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002727#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002728 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2729 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2730 Py_XDECREF(debug);
2731 return NULL;
2732 }
2733 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002734
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002735 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002736#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002737#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002738}
2739
Guido van Rossume77a7571993-11-03 15:01:26 +00002740/* Helper for filter(): filter a tuple through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002741
Guido van Rossum79f25d91997-04-29 20:08:16 +00002742static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002743filtertuple(PyObject *func, PyObject *tuple)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002744{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002745 PyObject *result;
2746 Py_ssize_t i, j;
2747 Py_ssize_t len = PyTuple_Size(tuple);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002748
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002749 if (len == 0) {
2750 if (PyTuple_CheckExact(tuple))
2751 Py_INCREF(tuple);
2752 else
2753 tuple = PyTuple_New(0);
2754 return tuple;
2755 }
Guido van Rossumb7b45621995-08-04 04:07:45 +00002756
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002757 if ((result = PyTuple_New(len)) == NULL)
2758 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002759
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002760 for (i = j = 0; i < len; ++i) {
2761 PyObject *item, *good;
2762 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002763
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002764 if (tuple->ob_type->tp_as_sequence &&
2765 tuple->ob_type->tp_as_sequence->sq_item) {
2766 item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
2767 if (item == NULL)
2768 goto Fail_1;
2769 } else {
2770 PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
2771 goto Fail_1;
2772 }
2773 if (func == Py_None) {
2774 Py_INCREF(item);
2775 good = item;
2776 }
2777 else {
2778 PyObject *arg = PyTuple_Pack(1, item);
2779 if (arg == NULL) {
2780 Py_DECREF(item);
2781 goto Fail_1;
2782 }
2783 good = PyEval_CallObject(func, arg);
2784 Py_DECREF(arg);
2785 if (good == NULL) {
2786 Py_DECREF(item);
2787 goto Fail_1;
2788 }
2789 }
2790 ok = PyObject_IsTrue(good);
2791 Py_DECREF(good);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002792 if (ok > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002793 if (PyTuple_SetItem(result, j++, item) < 0)
2794 goto Fail_1;
2795 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002796 else {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002797 Py_DECREF(item);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002798 if (ok < 0)
2799 goto Fail_1;
2800 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002801 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002802
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002803 if (_PyTuple_Resize(&result, j) < 0)
2804 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002805
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002806 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002807
Guido van Rossum12d12c51993-10-26 17:58:25 +00002808Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002809 Py_DECREF(result);
2810 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002811}
2812
2813
Guido van Rossume77a7571993-11-03 15:01:26 +00002814/* Helper for filter(): filter a string through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002815
Guido van Rossum79f25d91997-04-29 20:08:16 +00002816static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002817filterstring(PyObject *func, PyObject *strobj)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002818{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002819 PyObject *result;
2820 Py_ssize_t i, j;
2821 Py_ssize_t len = PyString_Size(strobj);
2822 Py_ssize_t outlen = len;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002823
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002824 if (func == Py_None) {
2825 /* If it's a real string we can return the original,
2826 * as no character is ever false and __getitem__
2827 * does return this character. If it's a subclass
2828 * we must go through the __getitem__ loop */
2829 if (PyString_CheckExact(strobj)) {
2830 Py_INCREF(strobj);
2831 return strobj;
2832 }
2833 }
2834 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2835 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002836
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002837 for (i = j = 0; i < len; ++i) {
2838 PyObject *item;
2839 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002840
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002841 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2842 if (item == NULL)
2843 goto Fail_1;
2844 if (func==Py_None) {
2845 ok = 1;
2846 } else {
2847 PyObject *arg, *good;
2848 arg = PyTuple_Pack(1, item);
2849 if (arg == NULL) {
2850 Py_DECREF(item);
2851 goto Fail_1;
2852 }
2853 good = PyEval_CallObject(func, arg);
2854 Py_DECREF(arg);
2855 if (good == NULL) {
2856 Py_DECREF(item);
2857 goto Fail_1;
2858 }
2859 ok = PyObject_IsTrue(good);
2860 Py_DECREF(good);
2861 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002862 if (ok > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002863 Py_ssize_t reslen;
2864 if (!PyString_Check(item)) {
2865 PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
2866 " __getitem__ returned different type");
2867 Py_DECREF(item);
2868 goto Fail_1;
2869 }
2870 reslen = PyString_GET_SIZE(item);
2871 if (reslen == 1) {
2872 PyString_AS_STRING(result)[j++] =
2873 PyString_AS_STRING(item)[0];
2874 } else {
2875 /* do we need more space? */
2876 Py_ssize_t need = j;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002877
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002878 /* calculate space requirements while checking for overflow */
2879 if (need > PY_SSIZE_T_MAX - reslen) {
2880 Py_DECREF(item);
2881 goto Fail_1;
2882 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002883
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002884 need += reslen;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002885
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002886 if (need > PY_SSIZE_T_MAX - len) {
2887 Py_DECREF(item);
2888 goto Fail_1;
2889 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002890
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002891 need += len;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002892
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002893 if (need <= i) {
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 = need - i - 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002899
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002900 assert(need >= 0);
2901 assert(outlen >= 0);
Gregory P. Smith9d534572008-06-11 07:41:16 +00002902
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002903 if (need > outlen) {
2904 /* overallocate, to avoid reallocations */
2905 if (outlen > PY_SSIZE_T_MAX / 2) {
2906 Py_DECREF(item);
2907 return NULL;
2908 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002909
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002910 if (need<2*outlen) {
2911 need = 2*outlen;
2912 }
2913 if (_PyString_Resize(&result, need)) {
2914 Py_DECREF(item);
2915 return NULL;
2916 }
2917 outlen = need;
2918 }
2919 memcpy(
2920 PyString_AS_STRING(result) + j,
2921 PyString_AS_STRING(item),
2922 reslen
2923 );
2924 j += reslen;
2925 }
2926 }
2927 Py_DECREF(item);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002928 if (ok < 0)
2929 goto Fail_1;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002930 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002931
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002932 if (j < outlen)
2933 _PyString_Resize(&result, j);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002934
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002935 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002936
Guido van Rossum12d12c51993-10-26 17:58:25 +00002937Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002938 Py_DECREF(result);
2939 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002940}
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002941
2942#ifdef Py_USING_UNICODE
2943/* Helper for filter(): filter a Unicode object through a function */
2944
2945static PyObject *
2946filterunicode(PyObject *func, PyObject *strobj)
2947{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002948 PyObject *result;
2949 register Py_ssize_t i, j;
2950 Py_ssize_t len = PyUnicode_GetSize(strobj);
2951 Py_ssize_t outlen = len;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002952
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002953 if (func == Py_None) {
2954 /* If it's a real string we can return the original,
2955 * as no character is ever false and __getitem__
2956 * does return this character. If it's a subclass
2957 * we must go through the __getitem__ loop */
2958 if (PyUnicode_CheckExact(strobj)) {
2959 Py_INCREF(strobj);
2960 return strobj;
2961 }
2962 }
2963 if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
2964 return NULL;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002965
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002966 for (i = j = 0; i < len; ++i) {
2967 PyObject *item, *arg, *good;
2968 int ok;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002969
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002970 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2971 if (item == NULL)
2972 goto Fail_1;
2973 if (func == Py_None) {
2974 ok = 1;
2975 } else {
2976 arg = PyTuple_Pack(1, item);
2977 if (arg == NULL) {
2978 Py_DECREF(item);
2979 goto Fail_1;
2980 }
2981 good = PyEval_CallObject(func, arg);
2982 Py_DECREF(arg);
2983 if (good == NULL) {
2984 Py_DECREF(item);
2985 goto Fail_1;
2986 }
2987 ok = PyObject_IsTrue(good);
2988 Py_DECREF(good);
2989 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002990 if (ok > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002991 Py_ssize_t reslen;
2992 if (!PyUnicode_Check(item)) {
2993 PyErr_SetString(PyExc_TypeError,
2994 "can't filter unicode to unicode:"
2995 " __getitem__ returned different type");
2996 Py_DECREF(item);
2997 goto Fail_1;
2998 }
2999 reslen = PyUnicode_GET_SIZE(item);
3000 if (reslen == 1)
3001 PyUnicode_AS_UNICODE(result)[j++] =
3002 PyUnicode_AS_UNICODE(item)[0];
3003 else {
3004 /* do we need more space? */
3005 Py_ssize_t need = j + reslen + len - i - 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003006
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003007 /* check that didnt overflow */
3008 if ((j > PY_SSIZE_T_MAX - reslen) ||
3009 ((j + reslen) > PY_SSIZE_T_MAX - len) ||
3010 ((j + reslen + len) < i) ||
3011 ((j + reslen + len - i) <= 0)) {
3012 Py_DECREF(item);
3013 return NULL;
3014 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00003015
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003016 assert(need >= 0);
3017 assert(outlen >= 0);
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003018
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003019 if (need > outlen) {
3020 /* overallocate,
3021 to avoid reallocations */
3022 if (need < 2 * outlen) {
3023 if (outlen > PY_SSIZE_T_MAX / 2) {
3024 Py_DECREF(item);
3025 return NULL;
3026 } else {
3027 need = 2 * outlen;
3028 }
3029 }
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003030
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003031 if (PyUnicode_Resize(
3032 &result, need) < 0) {
3033 Py_DECREF(item);
3034 goto Fail_1;
3035 }
3036 outlen = need;
3037 }
3038 memcpy(PyUnicode_AS_UNICODE(result) + j,
3039 PyUnicode_AS_UNICODE(item),
3040 reslen*sizeof(Py_UNICODE));
3041 j += reslen;
3042 }
3043 }
3044 Py_DECREF(item);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02003045 if (ok < 0)
3046 goto Fail_1;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003047 }
3048
3049 if (j < outlen)
3050 PyUnicode_Resize(&result, j);
3051
3052 return result;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003053
3054Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003055 Py_DECREF(result);
3056 return NULL;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003057}
3058#endif