blob: a07b78c8d984819e8613b7f95ef2f03981674f35 [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 Hammond26cffde42001-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 Hammond26cffde42001-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 Hammond26cffde42001-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();
526 mod = PyAST_obj2mod(cmd, arena, mode);
527 if (mod == NULL) {
528 PyArena_Free(arena);
529 return NULL;
530 }
531 result = (PyObject*)PyAST_Compile(mod, filename,
532 &cf, arena);
533 PyArena_Free(arena);
534 }
535 return result;
536 }
Georg Brandlfc8eef32008-03-28 12:11:56 +0000537
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000538#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000539 if (PyUnicode_Check(cmd)) {
540 tmp = PyUnicode_AsUTF8String(cmd);
541 if (tmp == NULL)
542 return NULL;
543 cmd = tmp;
544 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
545 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000546#endif
Tim Peters6cd6a822001-08-17 22:11:27 +0000547
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000548 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))
549 goto cleanup;
550 if ((size_t)length != strlen(str)) {
551 PyErr_SetString(PyExc_TypeError,
552 "compile() expected string without null bytes");
553 goto cleanup;
554 }
555 result = Py_CompileStringFlags(str, filename, start[mode], &cf);
Neal Norwitz3a9a3e72005-11-27 20:38:31 +0000556cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000557 Py_XDECREF(tmp);
558 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000559}
560
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000561PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000562"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000563\n\
564Compile the source string (a Python module, statement or expression)\n\
565into a code object that can be executed by the exec statement or eval().\n\
566The filename will be used for run-time error messages.\n\
567The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000568single (interactive) statement, or 'eval' to compile an expression.\n\
569The flags argument, if present, controls which future statements influence\n\
570the compilation of the code.\n\
571The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
572the effects of any future statements in effect in the code calling\n\
573compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000574in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000575
Guido van Rossum79f25d91997-04-29 20:08:16 +0000576static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000577builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000578{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000579 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000580
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000581 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
582 return NULL;
583 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000584}
585
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000586PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000587"dir([object]) -> list of strings\n"
588"\n"
Georg Brandl871f1bc2007-03-12 13:17:36 +0000589"If called without an argument, return the names in the current scope.\n"
590"Else, return an alphabetized list of names comprising (some of) the attributes\n"
591"of the given object, and of attributes reachable from it.\n"
592"If the object supplies a method named __dir__, it will be used; otherwise\n"
593"the default dir() logic is used and returns:\n"
594" for a module object: the module's attributes.\n"
595" for a class object: its attributes, and recursively the attributes\n"
596" of its bases.\n"
Georg Brandl3bb15672007-03-13 07:23:16 +0000597" for any other object: its attributes, its class's attributes, and\n"
Georg Brandl871f1bc2007-03-12 13:17:36 +0000598" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000599
Guido van Rossum79f25d91997-04-29 20:08:16 +0000600static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000601builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000602{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000603 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000604
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000605 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
606 return NULL;
607 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000608}
609
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000610PyDoc_STRVAR(divmod_doc,
Raymond Hettinger39540a02011-07-19 11:59:20 -0700611"divmod(x, y) -> (quotient, remainder)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000612\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000613Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000614
615
Guido van Rossum79f25d91997-04-29 20:08:16 +0000616static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000617builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000618{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000619 PyObject *cmd, *result, *tmp = NULL;
620 PyObject *globals = Py_None, *locals = Py_None;
621 char *str;
622 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000623
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000624 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
625 return NULL;
626 if (locals != Py_None && !PyMapping_Check(locals)) {
627 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
628 return NULL;
629 }
630 if (globals != Py_None && !PyDict_Check(globals)) {
631 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
632 "globals must be a real dict; try eval(expr, {}, mapping)"
633 : "globals must be a dict");
634 return NULL;
635 }
636 if (globals == Py_None) {
637 globals = PyEval_GetGlobals();
638 if (locals == Py_None)
639 locals = PyEval_GetLocals();
640 }
641 else if (locals == Py_None)
642 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000643
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000644 if (globals == NULL || locals == NULL) {
645 PyErr_SetString(PyExc_TypeError,
646 "eval must be given globals and locals "
647 "when called without a frame");
648 return NULL;
649 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000650
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000651 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
652 if (PyDict_SetItemString(globals, "__builtins__",
653 PyEval_GetBuiltins()) != 0)
654 return NULL;
655 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000656
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000657 if (PyCode_Check(cmd)) {
658 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
659 PyErr_SetString(PyExc_TypeError,
660 "code object passed to eval() may not contain free variables");
661 return NULL;
662 }
663 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
664 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000665
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000666 if (!PyString_Check(cmd) &&
667 !PyUnicode_Check(cmd)) {
668 PyErr_SetString(PyExc_TypeError,
669 "eval() arg 1 must be a string or code object");
670 return NULL;
671 }
672 cf.cf_flags = 0;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000673
674#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000675 if (PyUnicode_Check(cmd)) {
676 tmp = PyUnicode_AsUTF8String(cmd);
677 if (tmp == NULL)
678 return NULL;
679 cmd = tmp;
680 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
681 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000682#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000683 if (PyString_AsStringAndSize(cmd, &str, NULL)) {
684 Py_XDECREF(tmp);
685 return NULL;
686 }
687 while (*str == ' ' || *str == '\t')
688 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000689
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000690 (void)PyEval_MergeCompilerFlags(&cf);
691 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
692 Py_XDECREF(tmp);
693 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000694}
695
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000696PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000697"eval(source[, globals[, locals]]) -> value\n\
698\n\
699Evaluate the source in the context of globals and locals.\n\
700The source may be a string representing a Python expression\n\
701or a code object as returned by compile().\n\
Neal Norwitz477ca1c2006-09-05 02:25:41 +0000702The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000703defaulting to the current globals and locals.\n\
704If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000705
706
Guido van Rossum79f25d91997-04-29 20:08:16 +0000707static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000708builtin_execfile(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000709{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000710 char *filename;
711 PyObject *globals = Py_None, *locals = Py_None;
712 PyObject *res;
713 FILE* fp = NULL;
714 PyCompilerFlags cf;
715 int exists;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000716
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000717 if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
718 1) < 0)
719 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +0000720
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000721 if (!PyArg_ParseTuple(args, "s|O!O:execfile",
722 &filename,
723 &PyDict_Type, &globals,
724 &locals))
725 return NULL;
726 if (locals != Py_None && !PyMapping_Check(locals)) {
727 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
728 return NULL;
729 }
730 if (globals == Py_None) {
731 globals = PyEval_GetGlobals();
732 if (locals == Py_None)
733 locals = PyEval_GetLocals();
734 }
735 else if (locals == Py_None)
736 locals = globals;
737 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
738 if (PyDict_SetItemString(globals, "__builtins__",
739 PyEval_GetBuiltins()) != 0)
740 return NULL;
741 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000742
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000743 exists = 0;
744 /* Test for existence or directory. */
Martin v. Löwis3484a182002-03-09 12:07:51 +0000745#if defined(PLAN9)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000746 {
747 Dir *d;
Martin v. Löwis3484a182002-03-09 12:07:51 +0000748
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000749 if ((d = dirstat(filename))!=nil) {
750 if(d->mode & DMDIR)
751 werrstr("is a directory");
752 else
753 exists = 1;
754 free(d);
755 }
756 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000757#elif defined(RISCOS)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000758 if (object_exists(filename)) {
759 if (isdir(filename))
760 errno = EISDIR;
761 else
762 exists = 1;
763 }
764#else /* standard Posix */
765 {
766 struct stat s;
767 if (stat(filename, &s) == 0) {
768 if (S_ISDIR(s.st_mode))
769# if defined(PYOS_OS2) && defined(PYCC_VACPP)
770 errno = EOS2ERR;
771# else
772 errno = EISDIR;
773# endif
774 else
775 exists = 1;
776 }
777 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000778#endif
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000779
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000780 if (exists) {
781 Py_BEGIN_ALLOW_THREADS
782 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
783 Py_END_ALLOW_THREADS
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000784
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000785 if (fp == NULL) {
786 exists = 0;
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000787 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000788 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000789
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000790 if (!exists) {
791 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
792 return NULL;
793 }
794 cf.cf_flags = 0;
795 if (PyEval_MergeCompilerFlags(&cf))
796 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
797 locals, 1, &cf);
798 else
799 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
800 locals, 1);
801 return res;
Guido van Rossum0f61f8a1992-02-25 18:55:05 +0000802}
803
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000804PyDoc_STRVAR(execfile_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000805"execfile(filename[, globals[, locals]])\n\
806\n\
807Read and execute a Python script from a file.\n\
808The globals and locals are dictionaries, defaulting to the current\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000809globals and locals. If only globals is given, locals defaults to it.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000810
811
Guido van Rossum79f25d91997-04-29 20:08:16 +0000812static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000813builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000814{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000815 PyObject *v, *result, *dflt = NULL;
816 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000817
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000818 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
819 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000820#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000821 if (PyUnicode_Check(name)) {
822 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
823 if (name == NULL)
824 return NULL;
825 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000826#endif
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000827
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000828 if (!PyString_Check(name)) {
829 PyErr_SetString(PyExc_TypeError,
830 "getattr(): attribute name must be string");
831 return NULL;
832 }
833 result = PyObject_GetAttr(v, name);
834 if (result == NULL && dflt != NULL &&
835 PyErr_ExceptionMatches(PyExc_AttributeError))
836 {
837 PyErr_Clear();
838 Py_INCREF(dflt);
839 result = dflt;
840 }
841 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000842}
843
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000844PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000845"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000846\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000847Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
848When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000849exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000850
851
Guido van Rossum79f25d91997-04-29 20:08:16 +0000852static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000853builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000854{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000855 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000856
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000857 d = PyEval_GetGlobals();
858 Py_XINCREF(d);
859 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000860}
861
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000862PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000863"globals() -> dictionary\n\
864\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000865Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000866
867
Guido van Rossum79f25d91997-04-29 20:08:16 +0000868static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000869builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000870{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000871 PyObject *v;
872 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000873
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000874 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
875 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000876#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000877 if (PyUnicode_Check(name)) {
878 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
879 if (name == NULL)
880 return NULL;
881 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000882#endif
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000883
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000884 if (!PyString_Check(name)) {
885 PyErr_SetString(PyExc_TypeError,
886 "hasattr(): attribute name must be string");
887 return NULL;
888 }
889 v = PyObject_GetAttr(v, name);
890 if (v == NULL) {
891 if (!PyErr_ExceptionMatches(PyExc_Exception))
892 return NULL;
893 else {
894 PyErr_Clear();
895 Py_INCREF(Py_False);
896 return Py_False;
897 }
898 }
899 Py_DECREF(v);
900 Py_INCREF(Py_True);
901 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000902}
903
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000904PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000905"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000906\n\
907Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000908(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000909
910
Guido van Rossum79f25d91997-04-29 20:08:16 +0000911static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000912builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000913{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000914 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000915}
916
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000917PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000918"id(object) -> integer\n\
919\n\
920Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000921simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000922
923
Guido van Rossum79f25d91997-04-29 20:08:16 +0000924static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000925builtin_map(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000926{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000927 typedef struct {
928 PyObject *it; /* the iterator object */
929 int saw_StopIteration; /* bool: did the iterator end? */
930 } sequence;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000931
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000932 PyObject *func, *result;
933 sequence *seqs = NULL, *sqp;
934 Py_ssize_t n, len;
935 register int i, j;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000936
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000937 n = PyTuple_Size(args);
938 if (n < 2) {
939 PyErr_SetString(PyExc_TypeError,
940 "map() requires at least two args");
941 return NULL;
942 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000943
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000944 func = PyTuple_GetItem(args, 0);
945 n--;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000946
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000947 if (func == Py_None) {
948 if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
949 "use list(...)", 1) < 0)
950 return NULL;
951 if (n == 1) {
952 /* map(None, S) is the same as list(S). */
953 return PySequence_List(PyTuple_GetItem(args, 1));
954 }
955 }
Guido van Rossumfa4ac711998-07-10 17:37:30 +0000956
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000957 /* Get space for sequence descriptors. Must NULL out the iterator
958 * pointers so that jumping to Fail_2 later doesn't see trash.
959 */
960 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
961 PyErr_NoMemory();
962 return NULL;
963 }
964 for (i = 0; i < n; ++i) {
965 seqs[i].it = (PyObject*)NULL;
966 seqs[i].saw_StopIteration = 0;
967 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000968
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000969 /* Do a first pass to obtain iterators for the arguments, and set len
970 * to the largest of their lengths.
971 */
972 len = 0;
973 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
974 PyObject *curseq;
975 Py_ssize_t curlen;
Guido van Rossumad991772001-01-12 16:03:05 +0000976
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000977 /* Get iterator. */
978 curseq = PyTuple_GetItem(args, i+1);
979 sqp->it = PyObject_GetIter(curseq);
980 if (sqp->it == NULL) {
981 static char errmsg[] =
982 "argument %d to map() must support iteration";
983 char errbuf[sizeof(errmsg) + 25];
984 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
985 PyErr_SetString(PyExc_TypeError, errbuf);
986 goto Fail_2;
987 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000988
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000989 /* Update len. */
990 curlen = _PyObject_LengthHint(curseq, 8);
991 if (curlen > len)
992 len = curlen;
993 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000994
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000995 /* Get space for the result list. */
996 if ((result = (PyObject *) PyList_New(len)) == NULL)
997 goto Fail_2;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000998
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000999 /* Iterate over the sequences until all have stopped. */
1000 for (i = 0; ; ++i) {
1001 PyObject *alist, *item=NULL, *value;
1002 int numactive = 0;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001003
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001004 if (func == Py_None && n == 1)
1005 alist = NULL;
1006 else if ((alist = PyTuple_New(n)) == NULL)
1007 goto Fail_1;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001008
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001009 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
1010 if (sqp->saw_StopIteration) {
1011 Py_INCREF(Py_None);
1012 item = Py_None;
1013 }
1014 else {
1015 item = PyIter_Next(sqp->it);
1016 if (item)
1017 ++numactive;
1018 else {
1019 if (PyErr_Occurred()) {
1020 Py_XDECREF(alist);
1021 goto Fail_1;
1022 }
1023 Py_INCREF(Py_None);
1024 item = Py_None;
1025 sqp->saw_StopIteration = 1;
1026 }
1027 }
1028 if (alist)
1029 PyTuple_SET_ITEM(alist, j, item);
1030 else
1031 break;
1032 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001033
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001034 if (!alist)
1035 alist = item;
Guido van Rossum2d951851994-08-29 12:52:16 +00001036
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001037 if (numactive == 0) {
1038 Py_DECREF(alist);
1039 break;
1040 }
Guido van Rossum2d951851994-08-29 12:52:16 +00001041
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001042 if (func == Py_None)
1043 value = alist;
1044 else {
1045 value = PyEval_CallObject(func, alist);
1046 Py_DECREF(alist);
1047 if (value == NULL)
1048 goto Fail_1;
1049 }
1050 if (i >= len) {
1051 int status = PyList_Append(result, value);
1052 Py_DECREF(value);
1053 if (status < 0)
1054 goto Fail_1;
1055 }
1056 else if (PyList_SetItem(result, i, value) < 0)
1057 goto Fail_1;
1058 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001059
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001060 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
1061 goto Fail_1;
Guido van Rossumfa4ac711998-07-10 17:37:30 +00001062
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001063 goto Succeed;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001064
Guido van Rossum12d12c51993-10-26 17:58:25 +00001065Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001066 Py_DECREF(result);
Guido van Rossum12d12c51993-10-26 17:58:25 +00001067Fail_2:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001068 result = NULL;
Tim Peters4e9afdc2001-05-03 23:54:49 +00001069Succeed:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001070 assert(seqs);
1071 for (i = 0; i < n; ++i)
1072 Py_XDECREF(seqs[i].it);
1073 PyMem_DEL(seqs);
1074 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001075}
1076
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001077PyDoc_STRVAR(map_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001078"map(function, sequence[, sequence, ...]) -> list\n\
1079\n\
1080Return a list of the results of applying the function to the items of\n\
1081the argument sequence(s). If more than one sequence is given, the\n\
1082function is called with an argument list consisting of the corresponding\n\
1083item of each sequence, substituting None for missing values when not all\n\
1084sequences have the same length. If the function is None, return a list of\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001085the items of the sequence (or a list of tuples if more than one sequence).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001086
1087
Guido van Rossum79f25d91997-04-29 20:08:16 +00001088static PyObject *
Georg Brandl28e08732008-04-30 19:47:09 +00001089builtin_next(PyObject *self, PyObject *args)
1090{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001091 PyObject *it, *res;
1092 PyObject *def = NULL;
Georg Brandl28e08732008-04-30 19:47:09 +00001093
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001094 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1095 return NULL;
1096 if (!PyIter_Check(it)) {
1097 PyErr_Format(PyExc_TypeError,
1098 "%.200s object is not an iterator",
1099 it->ob_type->tp_name);
1100 return NULL;
1101 }
1102
1103 res = (*it->ob_type->tp_iternext)(it);
1104 if (res != NULL) {
1105 return res;
1106 } else if (def != NULL) {
1107 if (PyErr_Occurred()) {
1108 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
1109 return NULL;
1110 PyErr_Clear();
1111 }
1112 Py_INCREF(def);
1113 return def;
1114 } else if (PyErr_Occurred()) {
1115 return NULL;
1116 } else {
1117 PyErr_SetNone(PyExc_StopIteration);
1118 return NULL;
1119 }
Georg Brandl28e08732008-04-30 19:47:09 +00001120}
1121
1122PyDoc_STRVAR(next_doc,
1123"next(iterator[, default])\n\
1124\n\
1125Return the next item from the iterator. If default is given and the iterator\n\
1126is exhausted, it is returned instead of raising StopIteration.");
1127
1128
1129static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001130builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001131{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001132 PyObject *v;
1133 PyObject *name;
1134 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001135
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001136 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1137 return NULL;
1138 if (PyObject_SetAttr(v, name, value) != 0)
1139 return NULL;
1140 Py_INCREF(Py_None);
1141 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001142}
1143
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001144PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001145"setattr(object, name, value)\n\
1146\n\
1147Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001148``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001149
1150
Guido van Rossum79f25d91997-04-29 20:08:16 +00001151static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001152builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001153{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001154 PyObject *v;
1155 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001156
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001157 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1158 return NULL;
1159 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1160 return NULL;
1161 Py_INCREF(Py_None);
1162 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001163}
1164
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001165PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001166"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001167\n\
1168Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001169``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001170
1171
Guido van Rossum79f25d91997-04-29 20:08:16 +00001172static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001173builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001174{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001175 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001176
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001177 x = PyObject_Hash(v);
1178 if (x == -1)
1179 return NULL;
1180 return PyInt_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001181}
1182
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001183PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001184"hash(object) -> integer\n\
1185\n\
1186Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001187the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001188
1189
Guido van Rossum79f25d91997-04-29 20:08:16 +00001190static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001191builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001192{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001193 PyNumberMethods *nb;
1194 PyObject *res;
Benjamin Petersonc6d64ec2008-05-17 20:09:42 +00001195
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001196 if ((nb = v->ob_type->tp_as_number) == NULL ||
1197 nb->nb_hex == NULL) {
1198 PyErr_SetString(PyExc_TypeError,
1199 "hex() argument can't be converted to hex");
1200 return NULL;
1201 }
1202 res = (*nb->nb_hex)(v);
1203 if (res && !PyString_Check(res)) {
1204 PyErr_Format(PyExc_TypeError,
1205 "__hex__ returned non-string (type %.200s)",
1206 res->ob_type->tp_name);
1207 Py_DECREF(res);
1208 return NULL;
1209 }
1210 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001211}
1212
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001213PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001214"hex(number) -> string\n\
1215\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001216Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001217
1218
Tim Petersdbd9ba62000-07-09 03:09:57 +00001219static PyObject *builtin_raw_input(PyObject *, PyObject *);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001220
Guido van Rossum79f25d91997-04-29 20:08:16 +00001221static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001222builtin_input(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001223{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001224 PyObject *line;
1225 char *str;
1226 PyObject *res;
1227 PyObject *globals, *locals;
1228 PyCompilerFlags cf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001229
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001230 line = builtin_raw_input(self, args);
1231 if (line == NULL)
1232 return line;
1233 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1234 return NULL;
1235 while (*str == ' ' || *str == '\t')
1236 str++;
1237 globals = PyEval_GetGlobals();
1238 locals = PyEval_GetLocals();
1239 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1240 if (PyDict_SetItemString(globals, "__builtins__",
1241 PyEval_GetBuiltins()) != 0)
1242 return NULL;
1243 }
1244 cf.cf_flags = 0;
1245 PyEval_MergeCompilerFlags(&cf);
1246 res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1247 Py_DECREF(line);
1248 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001249}
1250
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001251PyDoc_STRVAR(input_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001252"input([prompt]) -> value\n\
1253\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001254Equivalent to eval(raw_input(prompt)).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001255
1256
Guido van Rossume8811f81997-02-14 15:48:05 +00001257static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001258builtin_intern(PyObject *self, PyObject *args)
Guido van Rossume8811f81997-02-14 15:48:05 +00001259{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001260 PyObject *s;
1261 if (!PyArg_ParseTuple(args, "S:intern", &s))
1262 return NULL;
1263 if (!PyString_CheckExact(s)) {
1264 PyErr_SetString(PyExc_TypeError,
1265 "can't intern subclass of string");
1266 return NULL;
1267 }
1268 Py_INCREF(s);
1269 PyString_InternInPlace(&s);
1270 return s;
Guido van Rossume8811f81997-02-14 15:48:05 +00001271}
1272
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001273PyDoc_STRVAR(intern_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001274"intern(string) -> string\n\
1275\n\
1276``Intern'' the given string. This enters the string in the (global)\n\
1277table of interned strings whose purpose is to speed up dictionary lookups.\n\
1278Return the string itself or the previously interned string object with the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001279same value.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001280
1281
Guido van Rossum79f25d91997-04-29 20:08:16 +00001282static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001283builtin_iter(PyObject *self, PyObject *args)
1284{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001285 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001286
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001287 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1288 return NULL;
1289 if (w == NULL)
1290 return PyObject_GetIter(v);
1291 if (!PyCallable_Check(v)) {
1292 PyErr_SetString(PyExc_TypeError,
1293 "iter(v, w): v must be callable");
1294 return NULL;
1295 }
1296 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001297}
1298
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001299PyDoc_STRVAR(iter_doc,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001300"iter(collection) -> iterator\n\
1301iter(callable, sentinel) -> iterator\n\
1302\n\
1303Get an iterator from an object. In the first form, the argument must\n\
1304supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001305In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001306
1307
1308static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001309builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001310{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001311 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001312
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001313 res = PyObject_Size(v);
1314 if (res < 0 && PyErr_Occurred())
1315 return NULL;
1316 return PyInt_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001317}
1318
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001319PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001320"len(object) -> integer\n\
1321\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001322Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001323
1324
Guido van Rossum79f25d91997-04-29 20:08:16 +00001325static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001326builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001327{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001328 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001329
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001330 d = PyEval_GetLocals();
1331 Py_XINCREF(d);
1332 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001333}
1334
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001335PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001336"locals() -> dictionary\n\
1337\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001338Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001339
1340
Guido van Rossum79f25d91997-04-29 20:08:16 +00001341static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001342min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001343{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001344 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1345 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001346
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001347 if (PyTuple_Size(args) > 1)
1348 v = args;
1349 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1350 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001351
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001352 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1353 keyfunc = PyDict_GetItemString(kwds, "key");
1354 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1355 PyErr_Format(PyExc_TypeError,
1356 "%s() got an unexpected keyword argument", name);
1357 return NULL;
1358 }
1359 Py_INCREF(keyfunc);
1360 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001361
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001362 it = PyObject_GetIter(v);
1363 if (it == NULL) {
1364 Py_XDECREF(keyfunc);
1365 return NULL;
1366 }
Tim Petersc3074532001-05-03 07:00:32 +00001367
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001368 maxitem = NULL; /* the result */
1369 maxval = NULL; /* the value associated with the result */
1370 while (( item = PyIter_Next(it) )) {
1371 /* get the value from the key function */
1372 if (keyfunc != NULL) {
1373 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1374 if (val == NULL)
1375 goto Fail_it_item;
1376 }
1377 /* no key function; the value is the item */
1378 else {
1379 val = item;
1380 Py_INCREF(val);
1381 }
Tim Petersc3074532001-05-03 07:00:32 +00001382
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001383 /* maximum value and item are unset; set them */
1384 if (maxval == NULL) {
1385 maxitem = item;
1386 maxval = val;
1387 }
1388 /* maximum value and item are set; update them as necessary */
1389 else {
1390 int cmp = PyObject_RichCompareBool(val, maxval, op);
1391 if (cmp < 0)
1392 goto Fail_it_item_and_val;
1393 else if (cmp > 0) {
1394 Py_DECREF(maxval);
1395 Py_DECREF(maxitem);
1396 maxval = val;
1397 maxitem = item;
1398 }
1399 else {
1400 Py_DECREF(item);
1401 Py_DECREF(val);
1402 }
1403 }
1404 }
1405 if (PyErr_Occurred())
1406 goto Fail_it;
1407 if (maxval == NULL) {
1408 PyErr_Format(PyExc_ValueError,
1409 "%s() arg is an empty sequence", name);
1410 assert(maxitem == NULL);
1411 }
1412 else
1413 Py_DECREF(maxval);
1414 Py_DECREF(it);
1415 Py_XDECREF(keyfunc);
1416 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001417
1418Fail_it_item_and_val:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001419 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001420Fail_it_item:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001421 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001422Fail_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001423 Py_XDECREF(maxval);
1424 Py_XDECREF(maxitem);
1425 Py_DECREF(it);
1426 Py_XDECREF(keyfunc);
1427 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001428}
1429
Guido van Rossum79f25d91997-04-29 20:08:16 +00001430static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001431builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001432{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001433 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001434}
1435
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001436PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001437"min(iterable[, key=func]) -> value\n\
1438min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001439\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001440With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001441With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001442
1443
Guido van Rossum79f25d91997-04-29 20:08:16 +00001444static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001445builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001446{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001447 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001448}
1449
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001450PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001451"max(iterable[, key=func]) -> value\n\
1452max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001453\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001454With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001455With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001456
1457
Guido van Rossum79f25d91997-04-29 20:08:16 +00001458static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001459builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001460{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001461 PyNumberMethods *nb;
1462 PyObject *res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001463
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001464 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1465 nb->nb_oct == NULL) {
1466 PyErr_SetString(PyExc_TypeError,
1467 "oct() argument can't be converted to oct");
1468 return NULL;
1469 }
1470 res = (*nb->nb_oct)(v);
1471 if (res && !PyString_Check(res)) {
1472 PyErr_Format(PyExc_TypeError,
1473 "__oct__ returned non-string (type %.200s)",
1474 res->ob_type->tp_name);
1475 Py_DECREF(res);
1476 return NULL;
1477 }
1478 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001479}
1480
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001481PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001482"oct(number) -> string\n\
1483\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001484Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001485
1486
Guido van Rossum79f25d91997-04-29 20:08:16 +00001487static PyObject *
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001488builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
1489{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001490 return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001491}
1492
1493PyDoc_STRVAR(open_doc,
1494"open(name[, mode[, buffering]]) -> file object\n\
1495\n\
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00001496Open a file using the file() type, returns a file object. This is the\n\
Philip Jenveydd0388a2009-05-28 03:12:16 +00001497preferred way to open a file. See file.__doc__ for further information.");
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001498
1499
1500static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001501builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001502{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001503 long ord;
1504 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001505
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001506 if (PyString_Check(obj)) {
1507 size = PyString_GET_SIZE(obj);
1508 if (size == 1) {
1509 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1510 return PyInt_FromLong(ord);
1511 }
1512 } else if (PyByteArray_Check(obj)) {
1513 size = PyByteArray_GET_SIZE(obj);
1514 if (size == 1) {
1515 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1516 return PyInt_FromLong(ord);
1517 }
Christian Heimes1a6387e2008-03-26 12:49:49 +00001518
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001519#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001520 } else if (PyUnicode_Check(obj)) {
1521 size = PyUnicode_GET_SIZE(obj);
1522 if (size == 1) {
1523 ord = (long)*PyUnicode_AS_UNICODE(obj);
1524 return PyInt_FromLong(ord);
1525 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001526#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001527 } else {
1528 PyErr_Format(PyExc_TypeError,
1529 "ord() expected string of length 1, but " \
1530 "%.200s found", obj->ob_type->tp_name);
1531 return NULL;
1532 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001533
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001534 PyErr_Format(PyExc_TypeError,
1535 "ord() expected a character, "
1536 "but string of length %zd found",
1537 size);
1538 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001539}
1540
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001541PyDoc_STRVAR(ord_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001542"ord(c) -> integer\n\
1543\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001544Return the integer ordinal of a one-character string.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001545
1546
Guido van Rossum79f25d91997-04-29 20:08:16 +00001547static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001548builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001549{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001550 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001551
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001552 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1553 return NULL;
1554 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001555}
1556
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001557PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001558"pow(x, y[, z]) -> number\n\
1559\n\
1560With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001561equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001562
1563
Eric Smith7c478942008-03-18 23:45:49 +00001564static PyObject *
1565builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1566{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001567 static char *kwlist[] = {"sep", "end", "file", 0};
1568 static PyObject *dummy_args = NULL;
1569 static PyObject *unicode_newline = NULL, *unicode_space = NULL;
1570 static PyObject *str_newline = NULL, *str_space = NULL;
1571 PyObject *newline, *space;
1572 PyObject *sep = NULL, *end = NULL, *file = NULL;
1573 int i, err, use_unicode = 0;
Eric Smith7c478942008-03-18 23:45:49 +00001574
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001575 if (dummy_args == NULL) {
1576 if (!(dummy_args = PyTuple_New(0)))
1577 return NULL;
1578 }
1579 if (str_newline == NULL) {
1580 str_newline = PyString_FromString("\n");
1581 if (str_newline == NULL)
1582 return NULL;
1583 str_space = PyString_FromString(" ");
1584 if (str_space == NULL) {
1585 Py_CLEAR(str_newline);
1586 return NULL;
1587 }
Martin v. Löwised11a5d2012-05-20 10:42:17 +02001588#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001589 unicode_newline = PyUnicode_FromString("\n");
1590 if (unicode_newline == NULL) {
1591 Py_CLEAR(str_newline);
1592 Py_CLEAR(str_space);
1593 return NULL;
1594 }
1595 unicode_space = PyUnicode_FromString(" ");
1596 if (unicode_space == NULL) {
1597 Py_CLEAR(str_newline);
1598 Py_CLEAR(str_space);
1599 Py_CLEAR(unicode_space);
1600 return NULL;
1601 }
Martin v. Löwised11a5d2012-05-20 10:42:17 +02001602#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001603 }
1604 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1605 kwlist, &sep, &end, &file))
1606 return NULL;
1607 if (file == NULL || file == Py_None) {
1608 file = PySys_GetObject("stdout");
1609 /* sys.stdout may be None when FILE* stdout isn't connected */
1610 if (file == Py_None)
1611 Py_RETURN_NONE;
1612 }
1613 if (sep == Py_None) {
1614 sep = NULL;
1615 }
1616 else if (sep) {
1617 if (PyUnicode_Check(sep)) {
1618 use_unicode = 1;
1619 }
1620 else if (!PyString_Check(sep)) {
1621 PyErr_Format(PyExc_TypeError,
1622 "sep must be None, str or unicode, not %.200s",
1623 sep->ob_type->tp_name);
1624 return NULL;
1625 }
1626 }
1627 if (end == Py_None)
1628 end = NULL;
1629 else if (end) {
1630 if (PyUnicode_Check(end)) {
1631 use_unicode = 1;
1632 }
1633 else if (!PyString_Check(end)) {
1634 PyErr_Format(PyExc_TypeError,
1635 "end must be None, str or unicode, not %.200s",
1636 end->ob_type->tp_name);
1637 return NULL;
1638 }
1639 }
Benjamin Peterson753d1622009-07-02 18:16:45 +00001640
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001641 if (!use_unicode) {
1642 for (i = 0; i < PyTuple_Size(args); i++) {
1643 if (PyUnicode_Check(PyTuple_GET_ITEM(args, i))) {
1644 use_unicode = 1;
1645 break;
1646 }
1647 }
1648 }
1649 if (use_unicode) {
1650 newline = unicode_newline;
1651 space = unicode_space;
1652 }
1653 else {
1654 newline = str_newline;
1655 space = str_space;
1656 }
Eric Smith7c478942008-03-18 23:45:49 +00001657
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001658 for (i = 0; i < PyTuple_Size(args); i++) {
1659 if (i > 0) {
1660 if (sep == NULL)
1661 err = PyFile_WriteObject(space, file,
1662 Py_PRINT_RAW);
1663 else
1664 err = PyFile_WriteObject(sep, file,
1665 Py_PRINT_RAW);
1666 if (err)
1667 return NULL;
1668 }
1669 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1670 Py_PRINT_RAW);
1671 if (err)
1672 return NULL;
1673 }
Eric Smith7c478942008-03-18 23:45:49 +00001674
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001675 if (end == NULL)
1676 err = PyFile_WriteObject(newline, file, Py_PRINT_RAW);
1677 else
1678 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1679 if (err)
1680 return NULL;
Eric Smith7c478942008-03-18 23:45:49 +00001681
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001682 Py_RETURN_NONE;
Eric Smith7c478942008-03-18 23:45:49 +00001683}
1684
1685PyDoc_STRVAR(print_doc,
1686"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
1687\n\
1688Prints the values to a stream, or to sys.stdout by default.\n\
1689Optional keyword arguments:\n\
1690file: a file-like object (stream); defaults to the current sys.stdout.\n\
1691sep: string inserted between values, default a space.\n\
1692end: string appended after the last value, default a newline.");
1693
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001694
1695/* Return number of items in range (lo, hi, step), when arguments are
1696 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1697 * & only if the true value is too large to fit in a signed long.
1698 * Arguments MUST return 1 with either PyInt_Check() or
1699 * PyLong_Check(). Return -1 when there is an error.
1700 */
1701static long
1702get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
1703{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001704 /* -------------------------------------------------------------
1705 Algorithm is equal to that of get_len_of_range(), but it operates
1706 on PyObjects (which are assumed to be PyLong or PyInt objects).
1707 ---------------------------------------------------------------*/
1708 long n;
1709 PyObject *diff = NULL;
1710 PyObject *one = NULL;
1711 PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
1712 /* holds sub-expression evaluations */
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001713
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001714 /* if (lo >= hi), return length of 0. */
1715 if (PyObject_Compare(lo, hi) >= 0)
1716 return 0;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001717
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001718 if ((one = PyLong_FromLong(1L)) == NULL)
1719 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001720
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001721 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
1722 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001723
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001724 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
1725 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001726
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001727 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
1728 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001729
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001730 if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
1731 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001732
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001733 n = PyLong_AsLong(tmp3);
1734 if (PyErr_Occurred()) { /* Check for Overflow */
1735 PyErr_Clear();
1736 goto Fail;
1737 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001738
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001739 Py_DECREF(tmp3);
1740 Py_DECREF(tmp2);
1741 Py_DECREF(diff);
1742 Py_DECREF(tmp1);
1743 Py_DECREF(one);
1744 return n;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001745
1746 Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001747 Py_XDECREF(tmp3);
1748 Py_XDECREF(tmp2);
1749 Py_XDECREF(diff);
1750 Py_XDECREF(tmp1);
1751 Py_XDECREF(one);
1752 return -1;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001753}
1754
Mark Dickinsona8d26682010-05-04 16:18:25 +00001755/* Helper function for handle_range_longs. If arg is int or long
1756 object, returns it with incremented reference count. If arg is
1757 float, raises type error. As a last resort, creates a new int by
1758 calling arg type's nb_int method if it is defined. Returns NULL
1759 and sets exception on error.
1760
1761 Returns a new reference to an int object. */
1762static PyObject *
1763get_range_long_argument(PyObject *arg, const char *name)
1764{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001765 PyObject *v;
1766 PyNumberMethods *nb;
1767 if (PyInt_Check(arg) || PyLong_Check(arg)) {
1768 Py_INCREF(arg);
1769 return arg;
1770 }
1771 if (PyFloat_Check(arg) ||
1772 (nb = Py_TYPE(arg)->tp_as_number) == NULL ||
1773 nb->nb_int == NULL) {
1774 PyErr_Format(PyExc_TypeError,
1775 "range() integer %s argument expected, got %s.",
1776 name, arg->ob_type->tp_name);
1777 return NULL;
1778 }
1779 v = nb->nb_int(arg);
1780 if (v == NULL)
1781 return NULL;
1782 if (PyInt_Check(v) || PyLong_Check(v))
1783 return v;
1784 Py_DECREF(v);
1785 PyErr_SetString(PyExc_TypeError,
1786 "__int__ should return int object");
1787 return NULL;
Mark Dickinsona8d26682010-05-04 16:18:25 +00001788}
1789
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001790/* An extension of builtin_range() that handles the case when PyLong
1791 * arguments are given. */
1792static PyObject *
Mark Dickinsonef9b4ab2010-05-04 16:19:06 +00001793handle_range_longs(PyObject *self, PyObject *args)
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001794{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001795 PyObject *ilow = NULL;
1796 PyObject *ihigh = NULL;
1797 PyObject *istep = NULL;
Tim Peters874e1f72003-04-13 22:13:08 +00001798
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001799 PyObject *low = NULL;
1800 PyObject *high = NULL;
1801 PyObject *step = NULL;
Mark Dickinsona8d26682010-05-04 16:18:25 +00001802
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001803 PyObject *curnum = NULL;
1804 PyObject *v = NULL;
1805 long bign;
1806 Py_ssize_t i, n;
1807 int cmp_result;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001808
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001809 PyObject *zero = PyLong_FromLong(0);
Tim Peters874e1f72003-04-13 22:13:08 +00001810
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001811 if (zero == NULL)
1812 return NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001813
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001814 if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
1815 Py_DECREF(zero);
1816 return NULL;
1817 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001818
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001819 /* Figure out which way we were called, supply defaults, and be
1820 * sure to incref everything so that the decrefs at the end
1821 * are correct. NB: ilow, ihigh and istep are borrowed references.
1822 */
1823 assert(ilow != NULL);
1824 if (ihigh == NULL) {
1825 /* only 1 arg -- it's the upper limit */
1826 ihigh = ilow;
1827 ilow = NULL;
1828 }
Mark Dickinsona8d26682010-05-04 16:18:25 +00001829
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001830 /* convert ihigh if necessary */
1831 assert(ihigh != NULL);
1832 high = get_range_long_argument(ihigh, "end");
1833 if (high == NULL)
1834 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001835
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001836 /* ihigh correct now; do ilow */
1837 if (ilow == NULL) {
1838 Py_INCREF(zero);
1839 low = zero;
1840 }
1841 else {
1842 low = get_range_long_argument(ilow, "start");
1843 if (low == NULL)
1844 goto Fail;
1845 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001846
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001847 /* ilow and ihigh correct now; do istep */
1848 if (istep == NULL)
1849 step = PyLong_FromLong(1);
1850 else
1851 step = get_range_long_argument(istep, "step");
1852 if (step == NULL)
1853 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001854
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001855 if (PyObject_Cmp(step, zero, &cmp_result) == -1)
1856 goto Fail;
Tim Peters874e1f72003-04-13 22:13:08 +00001857
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001858 if (cmp_result == 0) {
1859 PyErr_SetString(PyExc_ValueError,
1860 "range() step argument must not be zero");
1861 goto Fail;
1862 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001863
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001864 if (cmp_result > 0)
1865 bign = get_len_of_range_longs(low, high, step);
1866 else {
1867 PyObject *neg_step = PyNumber_Negative(step);
1868 if (neg_step == NULL)
1869 goto Fail;
1870 bign = get_len_of_range_longs(high, low, neg_step);
1871 Py_DECREF(neg_step);
1872 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001873
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001874 n = (Py_ssize_t)bign;
1875 if (bign < 0 || (long)n != bign) {
1876 PyErr_SetString(PyExc_OverflowError,
1877 "range() result has too many items");
1878 goto Fail;
1879 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001880
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001881 v = PyList_New(n);
1882 if (v == NULL)
1883 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001884
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001885 curnum = low;
1886 Py_INCREF(curnum);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001887
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001888 for (i = 0; i < n; i++) {
1889 PyObject *w = PyNumber_Long(curnum);
1890 PyObject *tmp_num;
1891 if (w == NULL)
1892 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001893
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001894 PyList_SET_ITEM(v, i, w);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001895
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001896 tmp_num = PyNumber_Add(curnum, step);
1897 if (tmp_num == NULL)
1898 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001899
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001900 Py_DECREF(curnum);
1901 curnum = tmp_num;
1902 }
1903 Py_DECREF(low);
1904 Py_DECREF(high);
1905 Py_DECREF(step);
1906 Py_DECREF(zero);
1907 Py_DECREF(curnum);
1908 return v;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001909
1910 Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001911 Py_XDECREF(low);
1912 Py_XDECREF(high);
1913 Py_XDECREF(step);
1914 Py_DECREF(zero);
1915 Py_XDECREF(curnum);
1916 Py_XDECREF(v);
1917 return NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001918}
1919
Guido van Rossum124eff01999-02-23 16:11:01 +00001920/* Return number of items in range/xrange (lo, hi, step). step > 0
1921 * required. Return a value < 0 if & only if the true value is too
1922 * large to fit in a signed long.
1923 */
1924static long
Thomas Wouterse28c2962000-07-23 22:21:32 +00001925get_len_of_range(long lo, long hi, long step)
Guido van Rossum124eff01999-02-23 16:11:01 +00001926{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001927 /* -------------------------------------------------------------
1928 If lo >= hi, the range is empty.
1929 Else if n values are in the range, the last one is
1930 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1931 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1932 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1933 the RHS is non-negative and so truncation is the same as the
1934 floor. Letting M be the largest positive long, the worst case
1935 for the RHS numerator is hi=M, lo=-M-1, and then
1936 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1937 precision to compute the RHS exactly.
1938 ---------------------------------------------------------------*/
1939 long n = 0;
1940 if (lo < hi) {
1941 unsigned long uhi = (unsigned long)hi;
1942 unsigned long ulo = (unsigned long)lo;
1943 unsigned long diff = uhi - ulo - 1;
1944 n = (long)(diff / (unsigned long)step + 1);
1945 }
1946 return n;
Guido van Rossum124eff01999-02-23 16:11:01 +00001947}
1948
Guido van Rossum79f25d91997-04-29 20:08:16 +00001949static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001950builtin_range(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001951{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001952 long ilow = 0, ihigh = 0, istep = 1;
1953 long bign;
1954 Py_ssize_t i, n;
Guido van Rossum124eff01999-02-23 16:11:01 +00001955
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001956 PyObject *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001957
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001958 if (PyTuple_Size(args) <= 1) {
1959 if (!PyArg_ParseTuple(args,
1960 "l;range() requires 1-3 int arguments",
1961 &ihigh)) {
1962 PyErr_Clear();
1963 return handle_range_longs(self, args);
1964 }
1965 }
1966 else {
1967 if (!PyArg_ParseTuple(args,
1968 "ll|l;range() requires 1-3 int arguments",
1969 &ilow, &ihigh, &istep)) {
1970 PyErr_Clear();
1971 return handle_range_longs(self, args);
1972 }
1973 }
1974 if (istep == 0) {
1975 PyErr_SetString(PyExc_ValueError,
1976 "range() step argument must not be zero");
1977 return NULL;
1978 }
1979 if (istep > 0)
1980 bign = get_len_of_range(ilow, ihigh, istep);
1981 else
1982 bign = get_len_of_range(ihigh, ilow, -istep);
1983 n = (Py_ssize_t)bign;
1984 if (bign < 0 || (long)n != bign) {
1985 PyErr_SetString(PyExc_OverflowError,
1986 "range() result has too many items");
1987 return NULL;
1988 }
1989 v = PyList_New(n);
1990 if (v == NULL)
1991 return NULL;
1992 for (i = 0; i < n; i++) {
1993 PyObject *w = PyInt_FromLong(ilow);
1994 if (w == NULL) {
1995 Py_DECREF(v);
1996 return NULL;
1997 }
1998 PyList_SET_ITEM(v, i, w);
1999 ilow += istep;
2000 }
2001 return v;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002002}
2003
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002004PyDoc_STRVAR(range_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002005"range([start,] stop[, step]) -> list of integers\n\
2006\n\
2007Return a list containing an arithmetic progression of integers.\n\
2008range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
2009When step is given, it specifies the increment (or decrement).\n\
2010For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002011These are exactly the valid indices for a list of 4 elements.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002012
2013
Guido van Rossum79f25d91997-04-29 20:08:16 +00002014static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002015builtin_raw_input(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002016{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002017 PyObject *v = NULL;
2018 PyObject *fin = PySys_GetObject("stdin");
2019 PyObject *fout = PySys_GetObject("stdout");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002020
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002021 if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
2022 return NULL;
Martin v. Löwis31d2df52002-08-14 15:46:02 +00002023
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002024 if (fin == NULL) {
2025 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
2026 return NULL;
2027 }
2028 if (fout == NULL) {
2029 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
2030 return NULL;
2031 }
2032 if (PyFile_SoftSpace(fout, 0)) {
2033 if (PyFile_WriteString(" ", fout) != 0)
2034 return NULL;
2035 }
2036 if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
2037 && isatty(fileno(PyFile_AsFile(fin)))
2038 && isatty(fileno(PyFile_AsFile(fout)))) {
2039 PyObject *po;
2040 char *prompt;
2041 char *s;
2042 PyObject *result;
2043 if (v != NULL) {
2044 po = PyObject_Str(v);
2045 if (po == NULL)
2046 return NULL;
2047 prompt = PyString_AsString(po);
2048 if (prompt == NULL)
2049 return NULL;
2050 }
2051 else {
2052 po = NULL;
2053 prompt = "";
2054 }
2055 s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
2056 prompt);
2057 Py_XDECREF(po);
2058 if (s == NULL) {
2059 if (!PyErr_Occurred())
2060 PyErr_SetNone(PyExc_KeyboardInterrupt);
2061 return NULL;
2062 }
2063 if (*s == '\0') {
2064 PyErr_SetNone(PyExc_EOFError);
2065 result = NULL;
2066 }
2067 else { /* strip trailing '\n' */
2068 size_t len = strlen(s);
2069 if (len > PY_SSIZE_T_MAX) {
2070 PyErr_SetString(PyExc_OverflowError,
2071 "[raw_]input: input too long");
2072 result = NULL;
2073 }
2074 else {
2075 result = PyString_FromStringAndSize(s, len-1);
2076 }
2077 }
2078 PyMem_FREE(s);
2079 return result;
2080 }
2081 if (v != NULL) {
2082 if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
2083 return NULL;
2084 }
2085 return PyFile_GetLine(fin, -1);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002086}
2087
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002088PyDoc_STRVAR(raw_input_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002089"raw_input([prompt]) -> string\n\
2090\n\
2091Read a string from standard input. The trailing newline is stripped.\n\
2092If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
2093On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002094is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002095
2096
Guido van Rossum79f25d91997-04-29 20:08:16 +00002097static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002098builtin_reduce(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002099{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002100 static PyObject *functools_reduce = NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002101
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002102 if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
2103 "use functools.reduce()", 1) < 0)
2104 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +00002105
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002106 if (functools_reduce == NULL) {
2107 PyObject *functools = PyImport_ImportModule("functools");
2108 if (functools == NULL)
2109 return NULL;
2110 functools_reduce = PyObject_GetAttrString(functools, "reduce");
2111 Py_DECREF(functools);
2112 if (functools_reduce == NULL)
2113 return NULL;
2114 }
2115 return PyObject_Call(functools_reduce, args, NULL);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002116}
2117
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002118PyDoc_STRVAR(reduce_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002119"reduce(function, sequence[, initial]) -> value\n\
2120\n\
2121Apply a function of two arguments cumulatively to the items of a sequence,\n\
2122from left to right, so as to reduce the sequence to a single value.\n\
2123For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
2124((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
2125of the sequence in the calculation, and serves as a default when the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002126sequence is empty.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002127
2128
Guido van Rossum79f25d91997-04-29 20:08:16 +00002129static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002130builtin_reload(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002131{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002132 if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
2133 1) < 0)
2134 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +00002135
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002136 return PyImport_ReloadModule(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002137}
2138
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002139PyDoc_STRVAR(reload_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002140"reload(module) -> module\n\
2141\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002142Reload the module. The module must have been successfully imported before.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002143
2144
Guido van Rossum79f25d91997-04-29 20:08:16 +00002145static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002146builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00002147{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002148 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002149}
2150
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002151PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002152"repr(object) -> string\n\
2153\n\
2154Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002155For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002156
2157
Guido van Rossum79f25d91997-04-29 20:08:16 +00002158static PyObject *
Georg Brandlccadf842006-03-31 18:54:53 +00002159builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002160{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002161 double x;
2162 PyObject *o_ndigits = NULL;
2163 Py_ssize_t ndigits;
2164 static char *kwlist[] = {"number", "ndigits", 0};
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002165
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002166 if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|O:round",
2167 kwlist, &x, &o_ndigits))
2168 return NULL;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002169
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002170 if (o_ndigits == NULL) {
2171 /* second argument defaults to 0 */
2172 ndigits = 0;
2173 }
2174 else {
2175 /* interpret 2nd argument as a Py_ssize_t; clip on overflow */
2176 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
2177 if (ndigits == -1 && PyErr_Occurred())
2178 return NULL;
2179 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002180
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002181 /* nans, infinities and zeros round to themselves */
2182 if (!Py_IS_FINITE(x) || x == 0.0)
2183 return PyFloat_FromDouble(x);
Mark Dickinsonbce78372009-11-24 10:54:58 +00002184
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002185 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
2186 always rounds to itself. For ndigits < NDIGITS_MIN, x always
2187 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002188#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
2189#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002190 if (ndigits > NDIGITS_MAX)
2191 /* return x */
2192 return PyFloat_FromDouble(x);
2193 else if (ndigits < NDIGITS_MIN)
2194 /* return 0.0, but with sign of x */
2195 return PyFloat_FromDouble(0.0*x);
2196 else
2197 /* finite x, and ndigits is not unreasonably large */
2198 /* _Py_double_round is defined in floatobject.c */
2199 return _Py_double_round(x, (int)ndigits);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002200#undef NDIGITS_MAX
2201#undef NDIGITS_MIN
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002202}
2203
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002204PyDoc_STRVAR(round_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002205"round(number[, ndigits]) -> floating point number\n\
2206\n\
2207Round a number to a given precision in decimal digits (default 0 digits).\n\
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +00002208This always returns a floating point number. Precision may be negative.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002209
Raymond Hettinger64958a12003-12-17 20:43:33 +00002210static PyObject *
2211builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2212{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002213 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
2214 PyObject *callable;
2215 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
2216 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002217
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002218 /* args 1-4 should match listsort in Objects/listobject.c */
2219 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
2220 kwlist, &seq, &compare, &keyfunc, &reverse))
2221 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002222
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002223 newlist = PySequence_List(seq);
2224 if (newlist == NULL)
2225 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002226
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002227 callable = PyObject_GetAttrString(newlist, "sort");
2228 if (callable == NULL) {
2229 Py_DECREF(newlist);
2230 return NULL;
2231 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002232
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002233 newargs = PyTuple_GetSlice(args, 1, 4);
2234 if (newargs == NULL) {
2235 Py_DECREF(newlist);
2236 Py_DECREF(callable);
2237 return NULL;
2238 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00002239
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002240 v = PyObject_Call(callable, newargs, kwds);
2241 Py_DECREF(newargs);
2242 Py_DECREF(callable);
2243 if (v == NULL) {
2244 Py_DECREF(newlist);
2245 return NULL;
2246 }
2247 Py_DECREF(v);
2248 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002249}
2250
2251PyDoc_STRVAR(sorted_doc,
2252"sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002253
Guido van Rossum79f25d91997-04-29 20:08:16 +00002254static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002255builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002256{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002257 PyObject *v = NULL;
2258 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002259
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002260 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2261 return NULL;
2262 if (v == NULL) {
2263 d = PyEval_GetLocals();
2264 if (d == NULL) {
2265 if (!PyErr_Occurred())
2266 PyErr_SetString(PyExc_SystemError,
2267 "vars(): no locals!?");
2268 }
2269 else
2270 Py_INCREF(d);
2271 }
2272 else {
2273 d = PyObject_GetAttrString(v, "__dict__");
2274 if (d == NULL) {
2275 PyErr_SetString(PyExc_TypeError,
2276 "vars() argument must have __dict__ attribute");
2277 return NULL;
2278 }
2279 }
2280 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002281}
2282
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002283PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002284"vars([object]) -> dictionary\n\
2285\n\
2286Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002287With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002288
Alex Martellia70b1912003-04-22 08:12:33 +00002289
2290static PyObject*
2291builtin_sum(PyObject *self, PyObject *args)
2292{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002293 PyObject *seq;
2294 PyObject *result = NULL;
2295 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002296
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002297 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
2298 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002299
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002300 iter = PyObject_GetIter(seq);
2301 if (iter == NULL)
2302 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002303
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002304 if (result == NULL) {
2305 result = PyInt_FromLong(0);
2306 if (result == NULL) {
2307 Py_DECREF(iter);
2308 return NULL;
2309 }
2310 } else {
2311 /* reject string values for 'start' parameter */
2312 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
2313 PyErr_SetString(PyExc_TypeError,
2314 "sum() can't sum strings [use ''.join(seq) instead]");
2315 Py_DECREF(iter);
2316 return NULL;
2317 }
2318 Py_INCREF(result);
2319 }
Alex Martellia70b1912003-04-22 08:12:33 +00002320
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002321#ifndef SLOW_SUM
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002322 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2323 Assumes all inputs are the same type. If the assumption fails, default
2324 to the more general routine.
2325 */
2326 if (PyInt_CheckExact(result)) {
2327 long i_result = PyInt_AS_LONG(result);
2328 Py_DECREF(result);
2329 result = NULL;
2330 while(result == NULL) {
2331 item = PyIter_Next(iter);
2332 if (item == NULL) {
2333 Py_DECREF(iter);
2334 if (PyErr_Occurred())
2335 return NULL;
2336 return PyInt_FromLong(i_result);
2337 }
2338 if (PyInt_CheckExact(item)) {
2339 long b = PyInt_AS_LONG(item);
2340 long x = i_result + b;
2341 if ((x^i_result) >= 0 || (x^b) >= 0) {
2342 i_result = x;
2343 Py_DECREF(item);
2344 continue;
2345 }
2346 }
2347 /* Either overflowed or is not an int. Restore real objects and process normally */
2348 result = PyInt_FromLong(i_result);
2349 temp = PyNumber_Add(result, item);
2350 Py_DECREF(result);
2351 Py_DECREF(item);
2352 result = temp;
2353 if (result == NULL) {
2354 Py_DECREF(iter);
2355 return NULL;
2356 }
2357 }
2358 }
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002359
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002360 if (PyFloat_CheckExact(result)) {
2361 double f_result = PyFloat_AS_DOUBLE(result);
2362 Py_DECREF(result);
2363 result = NULL;
2364 while(result == NULL) {
2365 item = PyIter_Next(iter);
2366 if (item == NULL) {
2367 Py_DECREF(iter);
2368 if (PyErr_Occurred())
2369 return NULL;
2370 return PyFloat_FromDouble(f_result);
2371 }
2372 if (PyFloat_CheckExact(item)) {
2373 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2374 f_result += PyFloat_AS_DOUBLE(item);
2375 PyFPE_END_PROTECT(f_result)
2376 Py_DECREF(item);
2377 continue;
2378 }
2379 if (PyInt_CheckExact(item)) {
2380 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2381 f_result += (double)PyInt_AS_LONG(item);
2382 PyFPE_END_PROTECT(f_result)
2383 Py_DECREF(item);
2384 continue;
2385 }
2386 result = PyFloat_FromDouble(f_result);
2387 temp = PyNumber_Add(result, item);
2388 Py_DECREF(result);
2389 Py_DECREF(item);
2390 result = temp;
2391 if (result == NULL) {
2392 Py_DECREF(iter);
2393 return NULL;
2394 }
2395 }
2396 }
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002397#endif
2398
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002399 for(;;) {
2400 item = PyIter_Next(iter);
2401 if (item == NULL) {
2402 /* error, or end-of-sequence */
2403 if (PyErr_Occurred()) {
2404 Py_DECREF(result);
2405 result = NULL;
2406 }
2407 break;
2408 }
2409 /* It's tempting to use PyNumber_InPlaceAdd instead of
2410 PyNumber_Add here, to avoid quadratic running time
2411 when doing 'sum(list_of_lists, [])'. However, this
2412 would produce a change in behaviour: a snippet like
Mark Dickinson0e0e2152009-10-26 14:18:44 +00002413
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002414 empty = []
2415 sum([[x] for x in range(10)], empty)
Mark Dickinson0e0e2152009-10-26 14:18:44 +00002416
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002417 would change the value of empty. */
2418 temp = PyNumber_Add(result, item);
2419 Py_DECREF(result);
2420 Py_DECREF(item);
2421 result = temp;
2422 if (result == NULL)
2423 break;
2424 }
2425 Py_DECREF(iter);
2426 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002427}
2428
2429PyDoc_STRVAR(sum_doc,
Georg Brandl8134d062006-10-12 12:33:07 +00002430"sum(sequence[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002431\n\
2432Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
Georg Brandl8134d062006-10-12 12:33:07 +00002433of parameter 'start' (which defaults to 0). When the sequence is\n\
2434empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002435
2436
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002437static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002438builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002439{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002440 PyObject *inst;
2441 PyObject *cls;
2442 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002443
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002444 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2445 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002446
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002447 retval = PyObject_IsInstance(inst, cls);
2448 if (retval < 0)
2449 return NULL;
2450 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002451}
2452
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002453PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002454"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002455\n\
2456Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002457With a type as second argument, return whether that is the object's type.\n\
2458The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002459isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002460
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002461
2462static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002463builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002464{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002465 PyObject *derived;
2466 PyObject *cls;
2467 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002468
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002469 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2470 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002471
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002472 retval = PyObject_IsSubclass(derived, cls);
2473 if (retval < 0)
2474 return NULL;
2475 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002476}
2477
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002478PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002479"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002480\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002481Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2482When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2483is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002484
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002485
Barry Warsawbd599b52000-08-03 15:45:29 +00002486static PyObject*
2487builtin_zip(PyObject *self, PyObject *args)
2488{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002489 PyObject *ret;
2490 const Py_ssize_t itemsize = PySequence_Length(args);
2491 Py_ssize_t i;
2492 PyObject *itlist; /* tuple of iterators */
2493 Py_ssize_t len; /* guess at result length */
Barry Warsawbd599b52000-08-03 15:45:29 +00002494
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002495 if (itemsize == 0)
2496 return PyList_New(0);
Raymond Hettingereaef6152003-08-02 07:42:57 +00002497
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002498 /* args must be a tuple */
2499 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002500
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002501 /* Guess at result length: the shortest of the input lengths.
2502 If some argument refuses to say, we refuse to guess too, lest
2503 an argument like xrange(sys.maxint) lead us astray.*/
2504 len = -1; /* unknown */
2505 for (i = 0; i < itemsize; ++i) {
2506 PyObject *item = PyTuple_GET_ITEM(args, i);
2507 Py_ssize_t thislen = _PyObject_LengthHint(item, -2);
2508 if (thislen < 0) {
2509 if (thislen == -1)
2510 return NULL;
2511 len = -1;
2512 break;
2513 }
2514 else if (len < 0 || thislen < len)
2515 len = thislen;
2516 }
Tim Peters67d687a2002-04-29 21:27:32 +00002517
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002518 /* allocate result list */
2519 if (len < 0)
2520 len = 10; /* arbitrary */
2521 if ((ret = PyList_New(len)) == NULL)
2522 return NULL;
Barry Warsawbd599b52000-08-03 15:45:29 +00002523
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002524 /* obtain iterators */
2525 itlist = PyTuple_New(itemsize);
2526 if (itlist == NULL)
2527 goto Fail_ret;
2528 for (i = 0; i < itemsize; ++i) {
2529 PyObject *item = PyTuple_GET_ITEM(args, i);
2530 PyObject *it = PyObject_GetIter(item);
2531 if (it == NULL) {
2532 if (PyErr_ExceptionMatches(PyExc_TypeError))
2533 PyErr_Format(PyExc_TypeError,
2534 "zip argument #%zd must support iteration",
2535 i+1);
2536 goto Fail_ret_itlist;
2537 }
2538 PyTuple_SET_ITEM(itlist, i, it);
2539 }
Barry Warsawbd599b52000-08-03 15:45:29 +00002540
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002541 /* build result into ret list */
2542 for (i = 0; ; ++i) {
2543 int j;
2544 PyObject *next = PyTuple_New(itemsize);
2545 if (!next)
2546 goto Fail_ret_itlist;
Tim Peters8572b4f2001-05-06 01:05:02 +00002547
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002548 for (j = 0; j < itemsize; j++) {
2549 PyObject *it = PyTuple_GET_ITEM(itlist, j);
2550 PyObject *item = PyIter_Next(it);
2551 if (!item) {
2552 if (PyErr_Occurred()) {
2553 Py_DECREF(ret);
2554 ret = NULL;
2555 }
2556 Py_DECREF(next);
2557 Py_DECREF(itlist);
2558 goto Done;
2559 }
2560 PyTuple_SET_ITEM(next, j, item);
2561 }
Tim Peters8572b4f2001-05-06 01:05:02 +00002562
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002563 if (i < len)
2564 PyList_SET_ITEM(ret, i, next);
2565 else {
2566 int status = PyList_Append(ret, next);
2567 Py_DECREF(next);
2568 ++len;
2569 if (status < 0)
2570 goto Fail_ret_itlist;
2571 }
2572 }
Tim Peters8572b4f2001-05-06 01:05:02 +00002573
Tim Peters67d687a2002-04-29 21:27:32 +00002574Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002575 if (ret != NULL && i < len) {
2576 /* The list is too big. */
2577 if (PyList_SetSlice(ret, i, len, NULL) < 0)
2578 return NULL;
2579 }
2580 return ret;
Tim Peters67d687a2002-04-29 21:27:32 +00002581
Tim Peters8572b4f2001-05-06 01:05:02 +00002582Fail_ret_itlist:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002583 Py_DECREF(itlist);
Tim Peters8572b4f2001-05-06 01:05:02 +00002584Fail_ret:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002585 Py_DECREF(ret);
2586 return NULL;
Barry Warsawbd599b52000-08-03 15:45:29 +00002587}
2588
2589
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002590PyDoc_STRVAR(zip_doc,
Barry Warsawbd599b52000-08-03 15:45:29 +00002591"zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2592\n\
2593Return a list of tuples, where each tuple contains the i-th element\n\
2594from each of the argument sequences. The returned list is truncated\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002595in length to the length of the shortest argument sequence.");
Barry Warsawbd599b52000-08-03 15:45:29 +00002596
2597
Guido van Rossum79f25d91997-04-29 20:08:16 +00002598static PyMethodDef builtin_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002599 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2600 {"abs", builtin_abs, METH_O, abs_doc},
2601 {"all", builtin_all, METH_O, all_doc},
2602 {"any", builtin_any, METH_O, any_doc},
2603 {"apply", builtin_apply, METH_VARARGS, apply_doc},
2604 {"bin", builtin_bin, METH_O, bin_doc},
2605 {"callable", builtin_callable, METH_O, callable_doc},
2606 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2607 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
2608 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
2609 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2610 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2611 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2612 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2613 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2614 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
2615 {"filter", builtin_filter, METH_VARARGS, filter_doc},
2616 {"format", builtin_format, METH_VARARGS, format_doc},
2617 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2618 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2619 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2620 {"hash", builtin_hash, METH_O, hash_doc},
2621 {"hex", builtin_hex, METH_O, hex_doc},
2622 {"id", builtin_id, METH_O, id_doc},
2623 {"input", builtin_input, METH_VARARGS, input_doc},
2624 {"intern", builtin_intern, METH_VARARGS, intern_doc},
2625 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2626 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2627 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2628 {"len", builtin_len, METH_O, len_doc},
2629 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2630 {"map", builtin_map, METH_VARARGS, map_doc},
2631 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2632 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2633 {"next", builtin_next, METH_VARARGS, next_doc},
2634 {"oct", builtin_oct, METH_O, oct_doc},
2635 {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
2636 {"ord", builtin_ord, METH_O, ord_doc},
2637 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2638 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2639 {"range", builtin_range, METH_VARARGS, range_doc},
2640 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
2641 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
2642 {"reload", builtin_reload, METH_O, reload_doc},
2643 {"repr", builtin_repr, METH_O, repr_doc},
2644 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2645 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2646 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2647 {"sum", builtin_sum, METH_VARARGS, sum_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002648#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002649 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002650#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002651 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2652 {"zip", builtin_zip, METH_VARARGS, zip_doc},
2653 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002654};
2655
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002656PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002657"Built-in functions, exceptions, and other objects.\n\
2658\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002659Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002660
Guido van Rossum25ce5661997-08-02 03:10:38 +00002661PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002662_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002663{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002664 PyObject *mod, *dict, *debug;
2665 mod = Py_InitModule4("__builtin__", builtin_methods,
2666 builtin_doc, (PyObject *)NULL,
2667 PYTHON_API_VERSION);
2668 if (mod == NULL)
2669 return NULL;
2670 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002671
Tim Peters7571a0f2003-03-23 17:52:28 +00002672#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002673 /* __builtin__ exposes a number of statically allocated objects
2674 * that, before this code was added in 2.3, never showed up in
2675 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2676 * result, programs leaking references to None and False (etc)
2677 * couldn't be diagnosed by examining sys.getobjects(0).
2678 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002679#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2680#else
2681#define ADD_TO_ALL(OBJECT) (void)0
2682#endif
2683
Tim Peters4b7625e2001-09-13 21:37:17 +00002684#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002685 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2686 return NULL; \
2687 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002688
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002689 SETBUILTIN("None", Py_None);
2690 SETBUILTIN("Ellipsis", Py_Ellipsis);
2691 SETBUILTIN("NotImplemented", Py_NotImplemented);
2692 SETBUILTIN("False", Py_False);
2693 SETBUILTIN("True", Py_True);
2694 SETBUILTIN("basestring", &PyBaseString_Type);
2695 SETBUILTIN("bool", &PyBool_Type);
2696 SETBUILTIN("memoryview", &PyMemoryView_Type);
2697 SETBUILTIN("bytearray", &PyByteArray_Type);
2698 SETBUILTIN("bytes", &PyString_Type);
2699 SETBUILTIN("buffer", &PyBuffer_Type);
2700 SETBUILTIN("classmethod", &PyClassMethod_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002701#ifndef WITHOUT_COMPLEX
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002702 SETBUILTIN("complex", &PyComplex_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002703#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002704 SETBUILTIN("dict", &PyDict_Type);
2705 SETBUILTIN("enumerate", &PyEnum_Type);
2706 SETBUILTIN("file", &PyFile_Type);
2707 SETBUILTIN("float", &PyFloat_Type);
2708 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2709 SETBUILTIN("property", &PyProperty_Type);
2710 SETBUILTIN("int", &PyInt_Type);
2711 SETBUILTIN("list", &PyList_Type);
2712 SETBUILTIN("long", &PyLong_Type);
2713 SETBUILTIN("object", &PyBaseObject_Type);
2714 SETBUILTIN("reversed", &PyReversed_Type);
2715 SETBUILTIN("set", &PySet_Type);
2716 SETBUILTIN("slice", &PySlice_Type);
2717 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2718 SETBUILTIN("str", &PyString_Type);
2719 SETBUILTIN("super", &PySuper_Type);
2720 SETBUILTIN("tuple", &PyTuple_Type);
2721 SETBUILTIN("type", &PyType_Type);
2722 SETBUILTIN("xrange", &PyRange_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002723#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002724 SETBUILTIN("unicode", &PyUnicode_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002725#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002726 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2727 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2728 Py_XDECREF(debug);
2729 return NULL;
2730 }
2731 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002732
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002733 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002734#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002735#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002736}
2737
Guido van Rossume77a7571993-11-03 15:01:26 +00002738/* Helper for filter(): filter a tuple through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002739
Guido van Rossum79f25d91997-04-29 20:08:16 +00002740static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002741filtertuple(PyObject *func, PyObject *tuple)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002742{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002743 PyObject *result;
2744 Py_ssize_t i, j;
2745 Py_ssize_t len = PyTuple_Size(tuple);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002746
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002747 if (len == 0) {
2748 if (PyTuple_CheckExact(tuple))
2749 Py_INCREF(tuple);
2750 else
2751 tuple = PyTuple_New(0);
2752 return tuple;
2753 }
Guido van Rossumb7b45621995-08-04 04:07:45 +00002754
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002755 if ((result = PyTuple_New(len)) == NULL)
2756 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002757
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002758 for (i = j = 0; i < len; ++i) {
2759 PyObject *item, *good;
2760 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002761
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002762 if (tuple->ob_type->tp_as_sequence &&
2763 tuple->ob_type->tp_as_sequence->sq_item) {
2764 item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
2765 if (item == NULL)
2766 goto Fail_1;
2767 } else {
2768 PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
2769 goto Fail_1;
2770 }
2771 if (func == Py_None) {
2772 Py_INCREF(item);
2773 good = item;
2774 }
2775 else {
2776 PyObject *arg = PyTuple_Pack(1, item);
2777 if (arg == NULL) {
2778 Py_DECREF(item);
2779 goto Fail_1;
2780 }
2781 good = PyEval_CallObject(func, arg);
2782 Py_DECREF(arg);
2783 if (good == NULL) {
2784 Py_DECREF(item);
2785 goto Fail_1;
2786 }
2787 }
2788 ok = PyObject_IsTrue(good);
2789 Py_DECREF(good);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002790 if (ok > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002791 if (PyTuple_SetItem(result, j++, item) < 0)
2792 goto Fail_1;
2793 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002794 else {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002795 Py_DECREF(item);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002796 if (ok < 0)
2797 goto Fail_1;
2798 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002799 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002800
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002801 if (_PyTuple_Resize(&result, j) < 0)
2802 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002803
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002804 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002805
Guido van Rossum12d12c51993-10-26 17:58:25 +00002806Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002807 Py_DECREF(result);
2808 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002809}
2810
2811
Guido van Rossume77a7571993-11-03 15:01:26 +00002812/* Helper for filter(): filter a string through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002813
Guido van Rossum79f25d91997-04-29 20:08:16 +00002814static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002815filterstring(PyObject *func, PyObject *strobj)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002816{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002817 PyObject *result;
2818 Py_ssize_t i, j;
2819 Py_ssize_t len = PyString_Size(strobj);
2820 Py_ssize_t outlen = len;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002821
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002822 if (func == Py_None) {
2823 /* If it's a real string we can return the original,
2824 * as no character is ever false and __getitem__
2825 * does return this character. If it's a subclass
2826 * we must go through the __getitem__ loop */
2827 if (PyString_CheckExact(strobj)) {
2828 Py_INCREF(strobj);
2829 return strobj;
2830 }
2831 }
2832 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2833 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002834
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002835 for (i = j = 0; i < len; ++i) {
2836 PyObject *item;
2837 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002838
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002839 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2840 if (item == NULL)
2841 goto Fail_1;
2842 if (func==Py_None) {
2843 ok = 1;
2844 } else {
2845 PyObject *arg, *good;
2846 arg = PyTuple_Pack(1, item);
2847 if (arg == NULL) {
2848 Py_DECREF(item);
2849 goto Fail_1;
2850 }
2851 good = PyEval_CallObject(func, arg);
2852 Py_DECREF(arg);
2853 if (good == NULL) {
2854 Py_DECREF(item);
2855 goto Fail_1;
2856 }
2857 ok = PyObject_IsTrue(good);
2858 Py_DECREF(good);
2859 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002860 if (ok > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002861 Py_ssize_t reslen;
2862 if (!PyString_Check(item)) {
2863 PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
2864 " __getitem__ returned different type");
2865 Py_DECREF(item);
2866 goto Fail_1;
2867 }
2868 reslen = PyString_GET_SIZE(item);
2869 if (reslen == 1) {
2870 PyString_AS_STRING(result)[j++] =
2871 PyString_AS_STRING(item)[0];
2872 } else {
2873 /* do we need more space? */
2874 Py_ssize_t need = j;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002875
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002876 /* calculate space requirements while checking for overflow */
2877 if (need > PY_SSIZE_T_MAX - reslen) {
2878 Py_DECREF(item);
2879 goto Fail_1;
2880 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002881
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002882 need += reslen;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002883
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002884 if (need > PY_SSIZE_T_MAX - len) {
2885 Py_DECREF(item);
2886 goto Fail_1;
2887 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002888
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002889 need += len;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002890
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002891 if (need <= i) {
2892 Py_DECREF(item);
2893 goto Fail_1;
2894 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002895
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002896 need = need - i - 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002897
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002898 assert(need >= 0);
2899 assert(outlen >= 0);
Gregory P. Smith9d534572008-06-11 07:41:16 +00002900
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002901 if (need > outlen) {
2902 /* overallocate, to avoid reallocations */
2903 if (outlen > PY_SSIZE_T_MAX / 2) {
2904 Py_DECREF(item);
2905 return NULL;
2906 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002907
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002908 if (need<2*outlen) {
2909 need = 2*outlen;
2910 }
2911 if (_PyString_Resize(&result, need)) {
2912 Py_DECREF(item);
2913 return NULL;
2914 }
2915 outlen = need;
2916 }
2917 memcpy(
2918 PyString_AS_STRING(result) + j,
2919 PyString_AS_STRING(item),
2920 reslen
2921 );
2922 j += reslen;
2923 }
2924 }
2925 Py_DECREF(item);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002926 if (ok < 0)
2927 goto Fail_1;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002928 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002929
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002930 if (j < outlen)
2931 _PyString_Resize(&result, j);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002932
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002933 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002934
Guido van Rossum12d12c51993-10-26 17:58:25 +00002935Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002936 Py_DECREF(result);
2937 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002938}
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002939
2940#ifdef Py_USING_UNICODE
2941/* Helper for filter(): filter a Unicode object through a function */
2942
2943static PyObject *
2944filterunicode(PyObject *func, PyObject *strobj)
2945{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002946 PyObject *result;
2947 register Py_ssize_t i, j;
2948 Py_ssize_t len = PyUnicode_GetSize(strobj);
2949 Py_ssize_t outlen = len;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002950
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002951 if (func == Py_None) {
2952 /* If it's a real string we can return the original,
2953 * as no character is ever false and __getitem__
2954 * does return this character. If it's a subclass
2955 * we must go through the __getitem__ loop */
2956 if (PyUnicode_CheckExact(strobj)) {
2957 Py_INCREF(strobj);
2958 return strobj;
2959 }
2960 }
2961 if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
2962 return NULL;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002963
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002964 for (i = j = 0; i < len; ++i) {
2965 PyObject *item, *arg, *good;
2966 int ok;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002967
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002968 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2969 if (item == NULL)
2970 goto Fail_1;
2971 if (func == Py_None) {
2972 ok = 1;
2973 } else {
2974 arg = PyTuple_Pack(1, item);
2975 if (arg == NULL) {
2976 Py_DECREF(item);
2977 goto Fail_1;
2978 }
2979 good = PyEval_CallObject(func, arg);
2980 Py_DECREF(arg);
2981 if (good == NULL) {
2982 Py_DECREF(item);
2983 goto Fail_1;
2984 }
2985 ok = PyObject_IsTrue(good);
2986 Py_DECREF(good);
2987 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002988 if (ok > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002989 Py_ssize_t reslen;
2990 if (!PyUnicode_Check(item)) {
2991 PyErr_SetString(PyExc_TypeError,
2992 "can't filter unicode to unicode:"
2993 " __getitem__ returned different type");
2994 Py_DECREF(item);
2995 goto Fail_1;
2996 }
2997 reslen = PyUnicode_GET_SIZE(item);
2998 if (reslen == 1)
2999 PyUnicode_AS_UNICODE(result)[j++] =
3000 PyUnicode_AS_UNICODE(item)[0];
3001 else {
3002 /* do we need more space? */
3003 Py_ssize_t need = j + reslen + len - i - 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003004
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003005 /* check that didnt overflow */
3006 if ((j > PY_SSIZE_T_MAX - reslen) ||
3007 ((j + reslen) > PY_SSIZE_T_MAX - len) ||
3008 ((j + reslen + len) < i) ||
3009 ((j + reslen + len - i) <= 0)) {
3010 Py_DECREF(item);
3011 return NULL;
3012 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00003013
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003014 assert(need >= 0);
3015 assert(outlen >= 0);
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003016
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003017 if (need > outlen) {
3018 /* overallocate,
3019 to avoid reallocations */
3020 if (need < 2 * outlen) {
3021 if (outlen > PY_SSIZE_T_MAX / 2) {
3022 Py_DECREF(item);
3023 return NULL;
3024 } else {
3025 need = 2 * outlen;
3026 }
3027 }
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003028
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003029 if (PyUnicode_Resize(
3030 &result, need) < 0) {
3031 Py_DECREF(item);
3032 goto Fail_1;
3033 }
3034 outlen = need;
3035 }
3036 memcpy(PyUnicode_AS_UNICODE(result) + j,
3037 PyUnicode_AS_UNICODE(item),
3038 reslen*sizeof(Py_UNICODE));
3039 j += reslen;
3040 }
3041 }
3042 Py_DECREF(item);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02003043 if (ok < 0)
3044 goto Fail_1;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003045 }
3046
3047 if (j < outlen)
3048 PyUnicode_Resize(&result, j);
3049
3050 return result;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003051
3052Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003053 Py_DECREF(result);
3054 return NULL;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003055}
3056#endif