blob: 0f2ee4ad1eb69f1ea72f8c6c92a50181f5a5c1b3 [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Georg Brandlfc8eef32008-03-28 12:11:56 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum5b722181993-03-30 17:46:03 +00008#include "eval.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00009
Guido van Rossum6bf62da1997-04-11 20:37:35 +000010#include <ctype.h>
Mark Dickinsonbd15a062009-11-18 19:33:35 +000011#include <float.h> /* for DBL_MANT_DIG and friends */
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012
Guido van Rossume2ae77b2001-10-24 20:42:55 +000013#ifdef RISCOS
14#include "unixstuff.h"
15#endif
16
Mark Hammond26cffde2001-05-14 12:17:34 +000017/* The default encoding used by the platform file system APIs
18 Can remain NULL for all platforms that don't have such a concept
19*/
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000020#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Mark Hammond26cffde2001-05-14 12:17:34 +000021const char *Py_FileSystemDefaultEncoding = "mbcs";
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000022#elif defined(__APPLE__)
23const char *Py_FileSystemDefaultEncoding = "utf-8";
Mark Hammond26cffde2001-05-14 12:17:34 +000024#else
25const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
26#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000027
Guido van Rossum12d12c51993-10-26 17:58:25 +000028/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000029static PyObject *filterstring(PyObject *, PyObject *);
Martin v. Löwis8afd7572003-01-25 22:46:11 +000030#ifdef Py_USING_UNICODE
31static PyObject *filterunicode(PyObject *, PyObject *);
32#endif
Tim Petersdbd9ba62000-07-09 03:09:57 +000033static PyObject *filtertuple (PyObject *, PyObject *);
Guido van Rossum12d12c51993-10-26 17:58:25 +000034
Guido van Rossum79f25d91997-04-29 20:08:16 +000035static PyObject *
Neal Norwitz92e212f2006-04-03 04:48:37 +000036builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +000037{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000038 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
39 "level", 0};
40 char *name;
41 PyObject *globals = NULL;
42 PyObject *locals = NULL;
43 PyObject *fromlist = NULL;
44 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +000045
Antoine Pitrouc83ea132010-05-09 14:46:46 +000046 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
47 kwlist, &name, &globals, &locals, &fromlist, &level))
48 return NULL;
49 return PyImport_ImportModuleLevel(name, globals, locals,
50 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +000051}
52
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000053PyDoc_STRVAR(import_doc,
Neal Norwitz92e212f2006-04-03 04:48:37 +000054"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000055\n\
R David Murray59488d22012-07-18 19:44:08 -040056Import a module. Because this function is meant for use by the Python\n\
57interpreter and not for general use it is better to use\n\
58importlib.import_module() to programmatically import a module.\n\
59\n\
60The globals argument is only used to determine the context;\n\
61they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000062should be a list of names to emulate ``from name import ...'', or an\n\
63empty list to emulate ``import name''.\n\
64When importing a module from a package, note that __import__('A.B', ...)\n\
65returns package A when fromlist is empty, but its submodule B when\n\
Neal Norwitz92e212f2006-04-03 04:48:37 +000066fromlist is not empty. Level is used to determine whether to perform \n\
67absolute or relative imports. -1 is the original strategy of attempting\n\
68both absolute and relative imports, 0 is absolute, a positive number\n\
69is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000070
Guido van Rossum1ae940a1995-01-02 19:04:15 +000071
Guido van Rossum79f25d91997-04-29 20:08:16 +000072static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000073builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +000074{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000075 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +000076}
77
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000078PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000079"abs(number) -> number\n\
80\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000081Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000082
Raymond Hettinger96229b12005-03-11 06:49:40 +000083static PyObject *
84builtin_all(PyObject *self, PyObject *v)
85{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000086 PyObject *it, *item;
87 PyObject *(*iternext)(PyObject *);
88 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +000089
Antoine Pitrouc83ea132010-05-09 14:46:46 +000090 it = PyObject_GetIter(v);
91 if (it == NULL)
92 return NULL;
93 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +000094
Antoine Pitrouc83ea132010-05-09 14:46:46 +000095 for (;;) {
96 item = iternext(it);
97 if (item == NULL)
98 break;
99 cmp = PyObject_IsTrue(item);
100 Py_DECREF(item);
101 if (cmp < 0) {
102 Py_DECREF(it);
103 return NULL;
104 }
105 if (cmp == 0) {
106 Py_DECREF(it);
107 Py_RETURN_FALSE;
108 }
109 }
110 Py_DECREF(it);
111 if (PyErr_Occurred()) {
112 if (PyErr_ExceptionMatches(PyExc_StopIteration))
113 PyErr_Clear();
114 else
115 return NULL;
116 }
117 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000118}
119
120PyDoc_STRVAR(all_doc,
121"all(iterable) -> bool\n\
122\n\
Ezio Melotti94bf6972013-02-15 23:35:14 +0200123Return True if bool(x) is True for all values x in the iterable.\n\
124If the iterable is empty, return True.");
Raymond Hettinger96229b12005-03-11 06:49:40 +0000125
126static PyObject *
127builtin_any(PyObject *self, PyObject *v)
128{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000129 PyObject *it, *item;
130 PyObject *(*iternext)(PyObject *);
131 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000132
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000133 it = PyObject_GetIter(v);
134 if (it == NULL)
135 return NULL;
136 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000137
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000138 for (;;) {
139 item = iternext(it);
140 if (item == NULL)
141 break;
142 cmp = PyObject_IsTrue(item);
143 Py_DECREF(item);
144 if (cmp < 0) {
145 Py_DECREF(it);
146 return NULL;
147 }
148 if (cmp == 1) {
149 Py_DECREF(it);
150 Py_RETURN_TRUE;
151 }
152 }
153 Py_DECREF(it);
154 if (PyErr_Occurred()) {
155 if (PyErr_ExceptionMatches(PyExc_StopIteration))
156 PyErr_Clear();
157 else
158 return NULL;
159 }
160 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000161}
162
163PyDoc_STRVAR(any_doc,
164"any(iterable) -> bool\n\
165\n\
Ezio Melotti94bf6972013-02-15 23:35:14 +0200166Return True if bool(x) is True for any x in the iterable.\n\
167If the iterable is empty, return False.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000168
Guido van Rossum79f25d91997-04-29 20:08:16 +0000169static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000170builtin_apply(PyObject *self, PyObject *args)
Guido van Rossumc02e15c1991-12-16 13:03:00 +0000171{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000172 PyObject *func, *alist = NULL, *kwdict = NULL;
173 PyObject *t = NULL, *retval = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000174
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000175 if (PyErr_WarnPy3k("apply() not supported in 3.x; "
176 "use func(*args, **kwargs)", 1) < 0)
177 return NULL;
Neal Norwitz8b2bfbc2007-05-23 06:35:32 +0000178
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000179 if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))
180 return NULL;
181 if (alist != NULL) {
182 if (!PyTuple_Check(alist)) {
183 if (!PySequence_Check(alist)) {
184 PyErr_Format(PyExc_TypeError,
185 "apply() arg 2 expected sequence, found %s",
186 alist->ob_type->tp_name);
187 return NULL;
188 }
189 t = PySequence_Tuple(alist);
190 if (t == NULL)
191 return NULL;
192 alist = t;
193 }
194 }
195 if (kwdict != NULL && !PyDict_Check(kwdict)) {
196 PyErr_Format(PyExc_TypeError,
197 "apply() arg 3 expected dictionary, found %s",
198 kwdict->ob_type->tp_name);
199 goto finally;
200 }
201 retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
Barry Warsaw968f8cb1998-10-01 15:33:12 +0000202 finally:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000203 Py_XDECREF(t);
204 return retval;
Guido van Rossumc02e15c1991-12-16 13:03:00 +0000205}
206
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000207PyDoc_STRVAR(apply_doc,
Fred Drakef1fbc622001-01-12 17:05:05 +0000208"apply(object[, args[, kwargs]]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000209\n\
Fred Drake7b912121999-12-23 14:16:55 +0000210Call a callable object with positional arguments taken from the tuple args,\n\
211and keyword arguments taken from the optional dictionary kwargs.\n\
Raymond Hettingerff41c482003-04-06 09:01:11 +0000212Note that classes are callable, as are instances with a __call__() method.\n\
213\n\
214Deprecated since release 2.3. Instead, use the extended call syntax:\n\
215 function(*args, **keywords).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000216
217
Guido van Rossum79f25d91997-04-29 20:08:16 +0000218static PyObject *
Eric Smith3cd81942008-02-22 16:30:22 +0000219builtin_bin(PyObject *self, PyObject *v)
220{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000221 return PyNumber_ToBase(v, 2);
Eric Smith3cd81942008-02-22 16:30:22 +0000222}
223
224PyDoc_STRVAR(bin_doc,
225"bin(number) -> string\n\
226\n\
227Return the binary representation of an integer or long integer.");
228
229
230static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000231builtin_callable(PyObject *self, PyObject *v)
Guido van Rossum2d951851994-08-29 12:52:16 +0000232{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000233 return PyBool_FromLong((long)PyCallable_Check(v));
Guido van Rossum2d951851994-08-29 12:52:16 +0000234}
235
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000236PyDoc_STRVAR(callable_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000237"callable(object) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000238\n\
239Return whether the object is callable (i.e., some kind of function).\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000240Note that classes are callable, as are instances with a __call__() method.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000241
242
Guido van Rossum79f25d91997-04-29 20:08:16 +0000243static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000244builtin_filter(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000245{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000246 PyObject *func, *seq, *result, *it, *arg;
247 Py_ssize_t len; /* guess for result list size */
248 register Py_ssize_t j;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000249
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000250 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
251 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000252
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000253 /* Strings and tuples return a result of the same type. */
254 if (PyString_Check(seq))
255 return filterstring(func, seq);
Martin v. Löwis8afd7572003-01-25 22:46:11 +0000256#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000257 if (PyUnicode_Check(seq))
258 return filterunicode(func, seq);
Martin v. Löwis8afd7572003-01-25 22:46:11 +0000259#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000260 if (PyTuple_Check(seq))
261 return filtertuple(func, seq);
Tim Peters0e57abf2001-05-02 07:39:38 +0000262
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000263 /* Pre-allocate argument list tuple. */
264 arg = PyTuple_New(1);
265 if (arg == NULL)
266 return NULL;
Georg Brandle35b6572005-07-19 22:20:20 +0000267
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000268 /* Get iterator. */
269 it = PyObject_GetIter(seq);
270 if (it == NULL)
271 goto Fail_arg;
Tim Peters0e57abf2001-05-02 07:39:38 +0000272
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000273 /* Guess a result list size. */
274 len = _PyObject_LengthHint(seq, 8);
275 if (len == -1)
276 goto Fail_it;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000277
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000278 /* Get a result list. */
279 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
280 /* Eww - can modify the list in-place. */
281 Py_INCREF(seq);
282 result = seq;
283 }
284 else {
285 result = PyList_New(len);
286 if (result == NULL)
287 goto Fail_it;
288 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000289
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000290 /* Build the result list. */
291 j = 0;
292 for (;;) {
293 PyObject *item;
294 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000295
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000296 item = PyIter_Next(it);
297 if (item == NULL) {
298 if (PyErr_Occurred())
299 goto Fail_result_it;
300 break;
301 }
Guido van Rossumdc4b93d1993-10-27 14:56:44 +0000302
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000303 if (func == (PyObject *)&PyBool_Type || func == Py_None) {
304 ok = PyObject_IsTrue(item);
305 }
306 else {
307 PyObject *good;
308 PyTuple_SET_ITEM(arg, 0, item);
309 good = PyObject_Call(func, arg, NULL);
310 PyTuple_SET_ITEM(arg, 0, NULL);
311 if (good == NULL) {
312 Py_DECREF(item);
313 goto Fail_result_it;
314 }
315 ok = PyObject_IsTrue(good);
316 Py_DECREF(good);
317 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +0200318 if (ok > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000319 if (j < len)
320 PyList_SET_ITEM(result, j, item);
321 else {
322 int status = PyList_Append(result, item);
323 Py_DECREF(item);
324 if (status < 0)
325 goto Fail_result_it;
326 }
327 ++j;
328 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +0200329 else {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000330 Py_DECREF(item);
Antoine Pitrouc5bef752012-08-15 23:16:51 +0200331 if (ok < 0)
332 goto Fail_result_it;
333 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000334 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000335
Guido van Rossum12d12c51993-10-26 17:58:25 +0000336
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000337 /* Cut back result list if len is too big. */
338 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
339 goto Fail_result_it;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000340
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000341 Py_DECREF(it);
342 Py_DECREF(arg);
343 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000344
Tim Peters0e57abf2001-05-02 07:39:38 +0000345Fail_result_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000346 Py_DECREF(result);
Tim Peters0e57abf2001-05-02 07:39:38 +0000347Fail_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000348 Py_DECREF(it);
Guido van Rossumc7903a12002-08-16 07:04:56 +0000349Fail_arg:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000350 Py_DECREF(arg);
351 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000352}
353
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000354PyDoc_STRVAR(filter_doc,
Tim Petersd50e5442002-03-09 00:06:26 +0000355"filter(function or None, sequence) -> list, tuple, or string\n"
356"\n"
357"Return those items of sequence for which function(item) is true. If\n"
358"function is None, return the items that are true. If sequence is a tuple\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000359"or string, return the same type, else return a list.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000360
Guido van Rossum79f25d91997-04-29 20:08:16 +0000361static PyObject *
Eric Smitha9f7d622008-02-17 19:46:49 +0000362builtin_format(PyObject *self, PyObject *args)
363{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000364 PyObject *value;
365 PyObject *format_spec = NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +0000366
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000367 if (!PyArg_ParseTuple(args, "O|O:format", &value, &format_spec))
368 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +0000369
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000370 return PyObject_Format(value, format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +0000371}
372
373PyDoc_STRVAR(format_doc,
374"format(value[, format_spec]) -> string\n\
375\n\
376Returns value.__format__(format_spec)\n\
Serhiy Storchaka6ed7aff2017-09-11 09:26:39 +0300377format_spec defaults to the empty string.\n\
378See the Format Specification Mini-Language section of help('FORMATTING') for\n\
379details.");
Eric Smitha9f7d622008-02-17 19:46:49 +0000380
381static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000382builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000383{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000384 long x;
385 char s[1];
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000386
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000387 if (!PyArg_ParseTuple(args, "l:chr", &x))
388 return NULL;
389 if (x < 0 || x >= 256) {
390 PyErr_SetString(PyExc_ValueError,
391 "chr() arg not in range(256)");
392 return NULL;
393 }
394 s[0] = (char)x;
395 return PyString_FromStringAndSize(s, 1);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000396}
397
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000398PyDoc_STRVAR(chr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000399"chr(i) -> character\n\
400\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000401Return a string of one character with ordinal i; 0 <= i < 256.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000402
403
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000404#ifdef Py_USING_UNICODE
Guido van Rossum79f25d91997-04-29 20:08:16 +0000405static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000406builtin_unichr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000407{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000408 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000409
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000410 if (!PyArg_ParseTuple(args, "i:unichr", &x))
411 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000412
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000413 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000414}
415
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000416PyDoc_STRVAR(unichr_doc,
Fred Drake078b24f2000-04-13 02:42:50 +0000417"unichr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000418\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000419Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000420#endif
Guido van Rossum09095f32000-03-10 23:00:52 +0000421
422
423static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000424builtin_cmp(PyObject *self, PyObject *args)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000425{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000426 PyObject *a, *b;
427 int c;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000428
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000429 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
430 return NULL;
431 if (PyObject_Cmp(a, b, &c) < 0)
432 return NULL;
433 return PyInt_FromLong((long)c);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000434}
435
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000436PyDoc_STRVAR(cmp_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000437"cmp(x, y) -> integer\n\
438\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000439Return negative if x<y, zero if x==y, positive if x>y.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000440
441
Guido van Rossum79f25d91997-04-29 20:08:16 +0000442static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000443builtin_coerce(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000444{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000445 PyObject *v, *w;
446 PyObject *res;
Guido van Rossum5524a591995-01-10 15:26:20 +0000447
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000448 if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
449 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +0000450
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000451 if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
452 return NULL;
453 if (PyNumber_Coerce(&v, &w) < 0)
454 return NULL;
455 res = PyTuple_Pack(2, v, w);
456 Py_DECREF(v);
457 Py_DECREF(w);
458 return res;
Guido van Rossum04691fc1992-08-12 15:35:34 +0000459}
460
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000461PyDoc_STRVAR(coerce_doc,
Martin v. Löwis8d494f32004-08-25 10:42:41 +0000462"coerce(x, y) -> (x1, y1)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000463\n\
Martin v. Löwis8d494f32004-08-25 10:42:41 +0000464Return a tuple consisting of the two numeric arguments converted to\n\
465a common type, using the same rules as used by arithmetic operations.\n\
466If coercion is not possible, raise TypeError.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000467
Guido van Rossum79f25d91997-04-29 20:08:16 +0000468static PyObject *
Georg Brandl5240d742007-03-13 20:46:32 +0000469builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000470{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000471 char *str;
472 char *filename;
473 char *startstr;
474 int mode = -1;
475 int dont_inherit = 0;
476 int supplied_flags = 0;
477 int is_ast;
478 PyCompilerFlags cf;
479 PyObject *result = NULL, *cmd, *tmp = NULL;
480 Py_ssize_t length;
481 static char *kwlist[] = {"source", "filename", "mode", "flags",
482 "dont_inherit", NULL};
483 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000484
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000485 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
486 kwlist, &cmd, &filename, &startstr,
487 &supplied_flags, &dont_inherit))
488 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000489
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000490 cf.cf_flags = supplied_flags;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000491
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000492 if (supplied_flags &
493 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
494 {
495 PyErr_SetString(PyExc_ValueError,
496 "compile(): unrecognised flags");
497 return NULL;
498 }
499 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Georg Brandlfc8eef32008-03-28 12:11:56 +0000500
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000501 if (!dont_inherit) {
502 PyEval_MergeCompilerFlags(&cf);
503 }
Georg Brandlfc8eef32008-03-28 12:11:56 +0000504
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000505 if (strcmp(startstr, "exec") == 0)
506 mode = 0;
507 else if (strcmp(startstr, "eval") == 0)
508 mode = 1;
509 else if (strcmp(startstr, "single") == 0)
510 mode = 2;
511 else {
512 PyErr_SetString(PyExc_ValueError,
513 "compile() arg 3 must be 'exec', 'eval' or 'single'");
514 return NULL;
515 }
Georg Brandlf2bfd542008-03-29 13:24:23 +0000516
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000517 is_ast = PyAST_Check(cmd);
518 if (is_ast == -1)
519 return NULL;
520 if (is_ast) {
521 if (supplied_flags & PyCF_ONLY_AST) {
522 Py_INCREF(cmd);
523 result = cmd;
524 }
525 else {
526 PyArena *arena;
527 mod_ty mod;
Georg Brandlfc8eef32008-03-28 12:11:56 +0000528
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000529 arena = PyArena_New();
Stefan Kraha8857af2012-08-20 17:31:22 +0200530 if (arena == NULL)
531 return NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000532 mod = PyAST_obj2mod(cmd, arena, mode);
533 if (mod == NULL) {
534 PyArena_Free(arena);
535 return NULL;
536 }
537 result = (PyObject*)PyAST_Compile(mod, filename,
538 &cf, arena);
539 PyArena_Free(arena);
540 }
541 return result;
542 }
Serhiy Storchaka61565602015-11-20 21:56:21 +0200543 if (PyString_Check(cmd)) {
544 str = PyString_AS_STRING(cmd);
545 length = PyString_GET_SIZE(cmd);
546 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000547#ifdef Py_USING_UNICODE
Serhiy Storchaka61565602015-11-20 21:56:21 +0200548 else if (PyUnicode_Check(cmd)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000549 tmp = PyUnicode_AsUTF8String(cmd);
550 if (tmp == NULL)
551 return NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000552 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
Serhiy Storchaka61565602015-11-20 21:56:21 +0200553 str = PyString_AS_STRING(tmp);
554 length = PyString_GET_SIZE(tmp);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000555 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000556#endif
Serhiy Storchaka61565602015-11-20 21:56:21 +0200557 else if (!PyObject_AsReadBuffer(cmd, (const void **)&str, &length)) {
558 /* Copy to NUL-terminated buffer. */
559 tmp = PyString_FromStringAndSize(str, length);
560 if (tmp == NULL)
561 return NULL;
562 str = PyString_AS_STRING(tmp);
563 length = PyString_GET_SIZE(tmp);
564 }
565 else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000566 goto cleanup;
567 if ((size_t)length != strlen(str)) {
568 PyErr_SetString(PyExc_TypeError,
569 "compile() expected string without null bytes");
570 goto cleanup;
571 }
572 result = Py_CompileStringFlags(str, filename, start[mode], &cf);
Neal Norwitz3a9a3e72005-11-27 20:38:31 +0000573cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000574 Py_XDECREF(tmp);
575 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000576}
577
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000578PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000579"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000580\n\
581Compile the source string (a Python module, statement or expression)\n\
582into a code object that can be executed by the exec statement or eval().\n\
583The filename will be used for run-time error messages.\n\
584The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000585single (interactive) statement, or 'eval' to compile an expression.\n\
586The flags argument, if present, controls which future statements influence\n\
587the compilation of the code.\n\
588The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
589the effects of any future statements in effect in the code calling\n\
590compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000591in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000592
Guido van Rossum79f25d91997-04-29 20:08:16 +0000593static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000594builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000595{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000596 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000597
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000598 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
599 return NULL;
600 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000601}
602
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000603PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000604"dir([object]) -> list of strings\n"
605"\n"
Georg Brandl871f1bc2007-03-12 13:17:36 +0000606"If called without an argument, return the names in the current scope.\n"
607"Else, return an alphabetized list of names comprising (some of) the attributes\n"
608"of the given object, and of attributes reachable from it.\n"
609"If the object supplies a method named __dir__, it will be used; otherwise\n"
610"the default dir() logic is used and returns:\n"
611" for a module object: the module's attributes.\n"
612" for a class object: its attributes, and recursively the attributes\n"
613" of its bases.\n"
Georg Brandl3bb15672007-03-13 07:23:16 +0000614" for any other object: its attributes, its class's attributes, and\n"
Georg Brandl871f1bc2007-03-12 13:17:36 +0000615" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000616
Guido van Rossum79f25d91997-04-29 20:08:16 +0000617static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000618builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000619{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000620 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000621
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000622 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
623 return NULL;
624 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000625}
626
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000627PyDoc_STRVAR(divmod_doc,
Raymond Hettinger39540a02011-07-19 11:59:20 -0700628"divmod(x, y) -> (quotient, remainder)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000629\n\
Zachary Warefd583492016-04-28 14:38:48 -0500630Return the tuple (x//y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000631
632
Guido van Rossum79f25d91997-04-29 20:08:16 +0000633static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000634builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000635{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000636 PyObject *cmd, *result, *tmp = NULL;
637 PyObject *globals = Py_None, *locals = Py_None;
638 char *str;
639 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000640
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000641 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
642 return NULL;
643 if (locals != Py_None && !PyMapping_Check(locals)) {
644 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
645 return NULL;
646 }
647 if (globals != Py_None && !PyDict_Check(globals)) {
648 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
649 "globals must be a real dict; try eval(expr, {}, mapping)"
650 : "globals must be a dict");
651 return NULL;
652 }
653 if (globals == Py_None) {
654 globals = PyEval_GetGlobals();
655 if (locals == Py_None)
656 locals = PyEval_GetLocals();
657 }
658 else if (locals == Py_None)
659 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000660
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000661 if (globals == NULL || locals == NULL) {
662 PyErr_SetString(PyExc_TypeError,
663 "eval must be given globals and locals "
664 "when called without a frame");
665 return NULL;
666 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000667
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000668 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
669 if (PyDict_SetItemString(globals, "__builtins__",
670 PyEval_GetBuiltins()) != 0)
671 return NULL;
672 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000673
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000674 if (PyCode_Check(cmd)) {
675 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
676 PyErr_SetString(PyExc_TypeError,
677 "code object passed to eval() may not contain free variables");
678 return NULL;
679 }
680 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
681 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000682
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000683 if (!PyString_Check(cmd) &&
684 !PyUnicode_Check(cmd)) {
685 PyErr_SetString(PyExc_TypeError,
686 "eval() arg 1 must be a string or code object");
687 return NULL;
688 }
689 cf.cf_flags = 0;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000690
691#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000692 if (PyUnicode_Check(cmd)) {
693 tmp = PyUnicode_AsUTF8String(cmd);
694 if (tmp == NULL)
695 return NULL;
696 cmd = tmp;
697 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
698 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000699#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000700 if (PyString_AsStringAndSize(cmd, &str, NULL)) {
701 Py_XDECREF(tmp);
702 return NULL;
703 }
704 while (*str == ' ' || *str == '\t')
705 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000706
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000707 (void)PyEval_MergeCompilerFlags(&cf);
708 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
709 Py_XDECREF(tmp);
710 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000711}
712
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000713PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000714"eval(source[, globals[, locals]]) -> value\n\
715\n\
716Evaluate the source in the context of globals and locals.\n\
717The source may be a string representing a Python expression\n\
718or a code object as returned by compile().\n\
Neal Norwitz477ca1c2006-09-05 02:25:41 +0000719The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000720defaulting to the current globals and locals.\n\
721If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000722
723
Guido van Rossum79f25d91997-04-29 20:08:16 +0000724static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000725builtin_execfile(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000726{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000727 char *filename;
728 PyObject *globals = Py_None, *locals = Py_None;
729 PyObject *res;
730 FILE* fp = NULL;
731 PyCompilerFlags cf;
732 int exists;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000733
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000734 if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
735 1) < 0)
736 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +0000737
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000738 if (!PyArg_ParseTuple(args, "s|O!O:execfile",
739 &filename,
740 &PyDict_Type, &globals,
741 &locals))
742 return NULL;
743 if (locals != Py_None && !PyMapping_Check(locals)) {
744 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
745 return NULL;
746 }
747 if (globals == Py_None) {
748 globals = PyEval_GetGlobals();
749 if (locals == Py_None)
750 locals = PyEval_GetLocals();
751 }
752 else if (locals == Py_None)
753 locals = globals;
754 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
755 if (PyDict_SetItemString(globals, "__builtins__",
756 PyEval_GetBuiltins()) != 0)
757 return NULL;
758 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000759
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000760 exists = 0;
761 /* Test for existence or directory. */
Martin v. Löwis3484a182002-03-09 12:07:51 +0000762#if defined(PLAN9)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000763 {
764 Dir *d;
Martin v. Löwis3484a182002-03-09 12:07:51 +0000765
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000766 if ((d = dirstat(filename))!=nil) {
767 if(d->mode & DMDIR)
768 werrstr("is a directory");
769 else
770 exists = 1;
771 free(d);
772 }
773 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000774#elif defined(RISCOS)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000775 if (object_exists(filename)) {
776 if (isdir(filename))
777 errno = EISDIR;
778 else
779 exists = 1;
780 }
781#else /* standard Posix */
782 {
783 struct stat s;
784 if (stat(filename, &s) == 0) {
785 if (S_ISDIR(s.st_mode))
786# if defined(PYOS_OS2) && defined(PYCC_VACPP)
787 errno = EOS2ERR;
788# else
789 errno = EISDIR;
790# endif
791 else
792 exists = 1;
793 }
794 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000795#endif
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000796
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000797 if (exists) {
798 Py_BEGIN_ALLOW_THREADS
799 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
800 Py_END_ALLOW_THREADS
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000801
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000802 if (fp == NULL) {
803 exists = 0;
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000804 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000805 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000806
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000807 if (!exists) {
808 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
809 return NULL;
810 }
811 cf.cf_flags = 0;
812 if (PyEval_MergeCompilerFlags(&cf))
813 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
814 locals, 1, &cf);
815 else
816 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
817 locals, 1);
818 return res;
Guido van Rossum0f61f8a1992-02-25 18:55:05 +0000819}
820
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000821PyDoc_STRVAR(execfile_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000822"execfile(filename[, globals[, locals]])\n\
823\n\
824Read and execute a Python script from a file.\n\
825The globals and locals are dictionaries, defaulting to the current\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000826globals and locals. If only globals is given, locals defaults to it.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000827
828
Guido van Rossum79f25d91997-04-29 20:08:16 +0000829static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000830builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000831{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000832 PyObject *v, *result, *dflt = NULL;
833 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000834
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000835 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
836 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000837#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000838 if (PyUnicode_Check(name)) {
839 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
840 if (name == NULL)
841 return NULL;
842 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000843#endif
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000844
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000845 if (!PyString_Check(name)) {
846 PyErr_SetString(PyExc_TypeError,
847 "getattr(): attribute name must be string");
848 return NULL;
849 }
850 result = PyObject_GetAttr(v, name);
851 if (result == NULL && dflt != NULL &&
852 PyErr_ExceptionMatches(PyExc_AttributeError))
853 {
854 PyErr_Clear();
855 Py_INCREF(dflt);
856 result = dflt;
857 }
858 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000859}
860
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000861PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000862"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000863\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000864Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
865When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000866exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000867
868
Guido van Rossum79f25d91997-04-29 20:08:16 +0000869static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000870builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000871{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000872 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000873
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000874 d = PyEval_GetGlobals();
875 Py_XINCREF(d);
876 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000877}
878
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000879PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000880"globals() -> dictionary\n\
881\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000882Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000883
884
Guido van Rossum79f25d91997-04-29 20:08:16 +0000885static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000886builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000887{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000888 PyObject *v;
889 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000890
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000891 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
892 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000893#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000894 if (PyUnicode_Check(name)) {
895 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
896 if (name == NULL)
897 return NULL;
898 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000899#endif
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000900
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000901 if (!PyString_Check(name)) {
902 PyErr_SetString(PyExc_TypeError,
903 "hasattr(): attribute name must be string");
904 return NULL;
905 }
906 v = PyObject_GetAttr(v, name);
907 if (v == NULL) {
908 if (!PyErr_ExceptionMatches(PyExc_Exception))
909 return NULL;
910 else {
911 PyErr_Clear();
912 Py_INCREF(Py_False);
913 return Py_False;
914 }
915 }
916 Py_DECREF(v);
917 Py_INCREF(Py_True);
918 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000919}
920
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000921PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000922"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000923\n\
924Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000925(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000926
927
Guido van Rossum79f25d91997-04-29 20:08:16 +0000928static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000929builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000930{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000931 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000932}
933
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000934PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000935"id(object) -> integer\n\
936\n\
937Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000938simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000939
940
Guido van Rossum79f25d91997-04-29 20:08:16 +0000941static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000942builtin_map(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000943{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000944 typedef struct {
945 PyObject *it; /* the iterator object */
946 int saw_StopIteration; /* bool: did the iterator end? */
947 } sequence;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000948
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000949 PyObject *func, *result;
950 sequence *seqs = NULL, *sqp;
951 Py_ssize_t n, len;
952 register int i, j;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000953
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000954 n = PyTuple_Size(args);
955 if (n < 2) {
956 PyErr_SetString(PyExc_TypeError,
957 "map() requires at least two args");
958 return NULL;
959 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000960
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000961 func = PyTuple_GetItem(args, 0);
962 n--;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000963
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000964 if (func == Py_None) {
965 if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
966 "use list(...)", 1) < 0)
967 return NULL;
968 if (n == 1) {
969 /* map(None, S) is the same as list(S). */
970 return PySequence_List(PyTuple_GetItem(args, 1));
971 }
972 }
Guido van Rossumfa4ac711998-07-10 17:37:30 +0000973
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000974 /* Get space for sequence descriptors. Must NULL out the iterator
975 * pointers so that jumping to Fail_2 later doesn't see trash.
976 */
977 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
978 PyErr_NoMemory();
979 return NULL;
980 }
981 for (i = 0; i < n; ++i) {
982 seqs[i].it = (PyObject*)NULL;
983 seqs[i].saw_StopIteration = 0;
984 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000985
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000986 /* Do a first pass to obtain iterators for the arguments, and set len
987 * to the largest of their lengths.
988 */
989 len = 0;
990 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
991 PyObject *curseq;
992 Py_ssize_t curlen;
Guido van Rossumad991772001-01-12 16:03:05 +0000993
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000994 /* Get iterator. */
995 curseq = PyTuple_GetItem(args, i+1);
996 sqp->it = PyObject_GetIter(curseq);
997 if (sqp->it == NULL) {
998 static char errmsg[] =
999 "argument %d to map() must support iteration";
1000 char errbuf[sizeof(errmsg) + 25];
1001 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
1002 PyErr_SetString(PyExc_TypeError, errbuf);
1003 goto Fail_2;
1004 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001005
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001006 /* Update len. */
1007 curlen = _PyObject_LengthHint(curseq, 8);
1008 if (curlen > len)
1009 len = curlen;
1010 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001011
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001012 /* Get space for the result list. */
1013 if ((result = (PyObject *) PyList_New(len)) == NULL)
1014 goto Fail_2;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001015
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001016 /* Iterate over the sequences until all have stopped. */
1017 for (i = 0; ; ++i) {
1018 PyObject *alist, *item=NULL, *value;
1019 int numactive = 0;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001020
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001021 if (func == Py_None && n == 1)
1022 alist = NULL;
1023 else if ((alist = PyTuple_New(n)) == NULL)
1024 goto Fail_1;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001025
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001026 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
1027 if (sqp->saw_StopIteration) {
1028 Py_INCREF(Py_None);
1029 item = Py_None;
1030 }
1031 else {
1032 item = PyIter_Next(sqp->it);
1033 if (item)
1034 ++numactive;
1035 else {
1036 if (PyErr_Occurred()) {
1037 Py_XDECREF(alist);
1038 goto Fail_1;
1039 }
1040 Py_INCREF(Py_None);
1041 item = Py_None;
1042 sqp->saw_StopIteration = 1;
1043 }
1044 }
1045 if (alist)
1046 PyTuple_SET_ITEM(alist, j, item);
1047 else
1048 break;
1049 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001050
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001051 if (!alist)
1052 alist = item;
Guido van Rossum2d951851994-08-29 12:52:16 +00001053
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001054 if (numactive == 0) {
1055 Py_DECREF(alist);
1056 break;
1057 }
Guido van Rossum2d951851994-08-29 12:52:16 +00001058
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001059 if (func == Py_None)
1060 value = alist;
1061 else {
1062 value = PyEval_CallObject(func, alist);
1063 Py_DECREF(alist);
1064 if (value == NULL)
1065 goto Fail_1;
1066 }
1067 if (i >= len) {
1068 int status = PyList_Append(result, value);
1069 Py_DECREF(value);
1070 if (status < 0)
1071 goto Fail_1;
1072 }
1073 else if (PyList_SetItem(result, i, value) < 0)
1074 goto Fail_1;
1075 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001076
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001077 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
1078 goto Fail_1;
Guido van Rossumfa4ac711998-07-10 17:37:30 +00001079
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001080 goto Succeed;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001081
Guido van Rossum12d12c51993-10-26 17:58:25 +00001082Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001083 Py_DECREF(result);
Guido van Rossum12d12c51993-10-26 17:58:25 +00001084Fail_2:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001085 result = NULL;
Tim Peters4e9afdc2001-05-03 23:54:49 +00001086Succeed:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001087 assert(seqs);
1088 for (i = 0; i < n; ++i)
1089 Py_XDECREF(seqs[i].it);
1090 PyMem_DEL(seqs);
1091 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001092}
1093
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001094PyDoc_STRVAR(map_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001095"map(function, sequence[, sequence, ...]) -> list\n\
1096\n\
1097Return a list of the results of applying the function to the items of\n\
1098the argument sequence(s). If more than one sequence is given, the\n\
1099function is called with an argument list consisting of the corresponding\n\
1100item of each sequence, substituting None for missing values when not all\n\
1101sequences have the same length. If the function is None, return a list of\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001102the items of the sequence (or a list of tuples if more than one sequence).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001103
1104
Guido van Rossum79f25d91997-04-29 20:08:16 +00001105static PyObject *
Georg Brandl28e08732008-04-30 19:47:09 +00001106builtin_next(PyObject *self, PyObject *args)
1107{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001108 PyObject *it, *res;
1109 PyObject *def = NULL;
Georg Brandl28e08732008-04-30 19:47:09 +00001110
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001111 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1112 return NULL;
1113 if (!PyIter_Check(it)) {
1114 PyErr_Format(PyExc_TypeError,
1115 "%.200s object is not an iterator",
1116 it->ob_type->tp_name);
1117 return NULL;
1118 }
1119
1120 res = (*it->ob_type->tp_iternext)(it);
1121 if (res != NULL) {
1122 return res;
1123 } else if (def != NULL) {
1124 if (PyErr_Occurred()) {
1125 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
1126 return NULL;
1127 PyErr_Clear();
1128 }
1129 Py_INCREF(def);
1130 return def;
1131 } else if (PyErr_Occurred()) {
1132 return NULL;
1133 } else {
1134 PyErr_SetNone(PyExc_StopIteration);
1135 return NULL;
1136 }
Georg Brandl28e08732008-04-30 19:47:09 +00001137}
1138
1139PyDoc_STRVAR(next_doc,
1140"next(iterator[, default])\n\
1141\n\
1142Return the next item from the iterator. If default is given and the iterator\n\
1143is exhausted, it is returned instead of raising StopIteration.");
1144
1145
1146static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001147builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001148{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001149 PyObject *v;
1150 PyObject *name;
1151 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001152
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001153 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1154 return NULL;
1155 if (PyObject_SetAttr(v, name, value) != 0)
1156 return NULL;
1157 Py_INCREF(Py_None);
1158 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001159}
1160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001161PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001162"setattr(object, name, value)\n\
1163\n\
1164Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001165``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001166
1167
Guido van Rossum79f25d91997-04-29 20:08:16 +00001168static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001169builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001170{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001171 PyObject *v;
1172 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001173
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001174 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1175 return NULL;
1176 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1177 return NULL;
1178 Py_INCREF(Py_None);
1179 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001180}
1181
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001182PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001183"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001184\n\
1185Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001186``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001187
1188
Guido van Rossum79f25d91997-04-29 20:08:16 +00001189static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001190builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001191{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001192 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001193
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001194 x = PyObject_Hash(v);
1195 if (x == -1)
1196 return NULL;
1197 return PyInt_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001198}
1199
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001200PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001201"hash(object) -> integer\n\
1202\n\
1203Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001204the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001205
1206
Guido van Rossum79f25d91997-04-29 20:08:16 +00001207static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001208builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001209{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001210 PyNumberMethods *nb;
1211 PyObject *res;
Benjamin Petersonc6d64ec2008-05-17 20:09:42 +00001212
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001213 if ((nb = v->ob_type->tp_as_number) == NULL ||
1214 nb->nb_hex == NULL) {
1215 PyErr_SetString(PyExc_TypeError,
1216 "hex() argument can't be converted to hex");
1217 return NULL;
1218 }
1219 res = (*nb->nb_hex)(v);
1220 if (res && !PyString_Check(res)) {
1221 PyErr_Format(PyExc_TypeError,
1222 "__hex__ returned non-string (type %.200s)",
1223 res->ob_type->tp_name);
1224 Py_DECREF(res);
1225 return NULL;
1226 }
1227 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001228}
1229
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001230PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001231"hex(number) -> string\n\
1232\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001233Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001234
1235
Tim Petersdbd9ba62000-07-09 03:09:57 +00001236static PyObject *builtin_raw_input(PyObject *, PyObject *);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001237
Guido van Rossum79f25d91997-04-29 20:08:16 +00001238static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001239builtin_input(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001240{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001241 PyObject *line;
1242 char *str;
1243 PyObject *res;
1244 PyObject *globals, *locals;
1245 PyCompilerFlags cf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001246
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001247 line = builtin_raw_input(self, args);
1248 if (line == NULL)
1249 return line;
1250 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1251 return NULL;
1252 while (*str == ' ' || *str == '\t')
1253 str++;
1254 globals = PyEval_GetGlobals();
1255 locals = PyEval_GetLocals();
1256 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1257 if (PyDict_SetItemString(globals, "__builtins__",
1258 PyEval_GetBuiltins()) != 0)
1259 return NULL;
1260 }
1261 cf.cf_flags = 0;
1262 PyEval_MergeCompilerFlags(&cf);
1263 res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1264 Py_DECREF(line);
1265 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001266}
1267
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001268PyDoc_STRVAR(input_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001269"input([prompt]) -> value\n\
1270\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001271Equivalent to eval(raw_input(prompt)).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001272
1273
Guido van Rossume8811f81997-02-14 15:48:05 +00001274static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001275builtin_intern(PyObject *self, PyObject *args)
Guido van Rossume8811f81997-02-14 15:48:05 +00001276{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001277 PyObject *s;
1278 if (!PyArg_ParseTuple(args, "S:intern", &s))
1279 return NULL;
1280 if (!PyString_CheckExact(s)) {
1281 PyErr_SetString(PyExc_TypeError,
1282 "can't intern subclass of string");
1283 return NULL;
1284 }
1285 Py_INCREF(s);
1286 PyString_InternInPlace(&s);
1287 return s;
Guido van Rossume8811f81997-02-14 15:48:05 +00001288}
1289
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001290PyDoc_STRVAR(intern_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001291"intern(string) -> string\n\
1292\n\
1293``Intern'' the given string. This enters the string in the (global)\n\
1294table of interned strings whose purpose is to speed up dictionary lookups.\n\
1295Return the string itself or the previously interned string object with the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001296same value.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001297
1298
Guido van Rossum79f25d91997-04-29 20:08:16 +00001299static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001300builtin_iter(PyObject *self, PyObject *args)
1301{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001302 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001303
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001304 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1305 return NULL;
1306 if (w == NULL)
1307 return PyObject_GetIter(v);
1308 if (!PyCallable_Check(v)) {
1309 PyErr_SetString(PyExc_TypeError,
1310 "iter(v, w): v must be callable");
1311 return NULL;
1312 }
1313 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001314}
1315
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001316PyDoc_STRVAR(iter_doc,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001317"iter(collection) -> iterator\n\
1318iter(callable, sentinel) -> iterator\n\
1319\n\
1320Get an iterator from an object. In the first form, the argument must\n\
1321supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001322In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001323
1324
1325static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001326builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001327{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001328 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001329
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001330 res = PyObject_Size(v);
1331 if (res < 0 && PyErr_Occurred())
1332 return NULL;
1333 return PyInt_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001334}
1335
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001336PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001337"len(object) -> integer\n\
1338\n\
Terry Jan Reedy9f2dcd22014-06-16 03:05:30 -04001339Return the number of items of a sequence or collection.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001340
1341
Guido van Rossum79f25d91997-04-29 20:08:16 +00001342static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001343builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001344{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001345 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001346
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001347 d = PyEval_GetLocals();
1348 Py_XINCREF(d);
1349 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001350}
1351
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001352PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001353"locals() -> dictionary\n\
1354\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001355Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001356
1357
Guido van Rossum79f25d91997-04-29 20:08:16 +00001358static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001359min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001360{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001361 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1362 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001363
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001364 if (PyTuple_Size(args) > 1)
1365 v = args;
1366 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1367 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001368
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001369 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1370 keyfunc = PyDict_GetItemString(kwds, "key");
1371 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1372 PyErr_Format(PyExc_TypeError,
1373 "%s() got an unexpected keyword argument", name);
1374 return NULL;
1375 }
1376 Py_INCREF(keyfunc);
1377 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001378
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001379 it = PyObject_GetIter(v);
1380 if (it == NULL) {
1381 Py_XDECREF(keyfunc);
1382 return NULL;
1383 }
Tim Petersc3074532001-05-03 07:00:32 +00001384
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001385 maxitem = NULL; /* the result */
1386 maxval = NULL; /* the value associated with the result */
1387 while (( item = PyIter_Next(it) )) {
1388 /* get the value from the key function */
1389 if (keyfunc != NULL) {
1390 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1391 if (val == NULL)
1392 goto Fail_it_item;
1393 }
1394 /* no key function; the value is the item */
1395 else {
1396 val = item;
1397 Py_INCREF(val);
1398 }
Tim Petersc3074532001-05-03 07:00:32 +00001399
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001400 /* maximum value and item are unset; set them */
1401 if (maxval == NULL) {
1402 maxitem = item;
1403 maxval = val;
1404 }
1405 /* maximum value and item are set; update them as necessary */
1406 else {
1407 int cmp = PyObject_RichCompareBool(val, maxval, op);
1408 if (cmp < 0)
1409 goto Fail_it_item_and_val;
1410 else if (cmp > 0) {
1411 Py_DECREF(maxval);
1412 Py_DECREF(maxitem);
1413 maxval = val;
1414 maxitem = item;
1415 }
1416 else {
1417 Py_DECREF(item);
1418 Py_DECREF(val);
1419 }
1420 }
1421 }
1422 if (PyErr_Occurred())
1423 goto Fail_it;
1424 if (maxval == NULL) {
1425 PyErr_Format(PyExc_ValueError,
1426 "%s() arg is an empty sequence", name);
1427 assert(maxitem == NULL);
1428 }
1429 else
1430 Py_DECREF(maxval);
1431 Py_DECREF(it);
1432 Py_XDECREF(keyfunc);
1433 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001434
1435Fail_it_item_and_val:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001436 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001437Fail_it_item:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001438 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001439Fail_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001440 Py_XDECREF(maxval);
1441 Py_XDECREF(maxitem);
1442 Py_DECREF(it);
1443 Py_XDECREF(keyfunc);
1444 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001445}
1446
Guido van Rossum79f25d91997-04-29 20:08:16 +00001447static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001448builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001449{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001450 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001451}
1452
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001453PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001454"min(iterable[, key=func]) -> value\n\
1455min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001456\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001457With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001458With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001459
1460
Guido van Rossum79f25d91997-04-29 20:08:16 +00001461static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001462builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001463{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001464 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001465}
1466
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001467PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001468"max(iterable[, key=func]) -> value\n\
1469max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001470\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001471With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001472With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001473
1474
Guido van Rossum79f25d91997-04-29 20:08:16 +00001475static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001476builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001477{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001478 PyNumberMethods *nb;
1479 PyObject *res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001480
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001481 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1482 nb->nb_oct == NULL) {
1483 PyErr_SetString(PyExc_TypeError,
1484 "oct() argument can't be converted to oct");
1485 return NULL;
1486 }
1487 res = (*nb->nb_oct)(v);
1488 if (res && !PyString_Check(res)) {
1489 PyErr_Format(PyExc_TypeError,
1490 "__oct__ returned non-string (type %.200s)",
1491 res->ob_type->tp_name);
1492 Py_DECREF(res);
1493 return NULL;
1494 }
1495 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001496}
1497
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001498PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001499"oct(number) -> string\n\
1500\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001501Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001502
1503
Guido van Rossum79f25d91997-04-29 20:08:16 +00001504static PyObject *
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001505builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
1506{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001507 return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001508}
1509
1510PyDoc_STRVAR(open_doc,
1511"open(name[, mode[, buffering]]) -> file object\n\
1512\n\
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00001513Open a file using the file() type, returns a file object. This is the\n\
Philip Jenveydd0388a2009-05-28 03:12:16 +00001514preferred way to open a file. See file.__doc__ for further information.");
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001515
1516
1517static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001518builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001519{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001520 long ord;
1521 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001522
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001523 if (PyString_Check(obj)) {
1524 size = PyString_GET_SIZE(obj);
1525 if (size == 1) {
1526 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1527 return PyInt_FromLong(ord);
1528 }
1529 } else if (PyByteArray_Check(obj)) {
1530 size = PyByteArray_GET_SIZE(obj);
1531 if (size == 1) {
1532 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1533 return PyInt_FromLong(ord);
1534 }
Christian Heimes1a6387e2008-03-26 12:49:49 +00001535
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001536#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001537 } else if (PyUnicode_Check(obj)) {
1538 size = PyUnicode_GET_SIZE(obj);
1539 if (size == 1) {
1540 ord = (long)*PyUnicode_AS_UNICODE(obj);
1541 return PyInt_FromLong(ord);
1542 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001543#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001544 } else {
1545 PyErr_Format(PyExc_TypeError,
1546 "ord() expected string of length 1, but " \
1547 "%.200s found", obj->ob_type->tp_name);
1548 return NULL;
1549 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001550
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001551 PyErr_Format(PyExc_TypeError,
1552 "ord() expected a character, "
1553 "but string of length %zd found",
1554 size);
1555 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001556}
1557
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001558PyDoc_STRVAR(ord_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001559"ord(c) -> integer\n\
1560\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001561Return the integer ordinal of a one-character string.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001562
1563
Guido van Rossum79f25d91997-04-29 20:08:16 +00001564static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001565builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001566{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001567 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001568
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001569 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1570 return NULL;
1571 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001572}
1573
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001574PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001575"pow(x, y[, z]) -> number\n\
1576\n\
1577With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001578equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001579
1580
Eric Smith7c478942008-03-18 23:45:49 +00001581static PyObject *
1582builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1583{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001584 static char *kwlist[] = {"sep", "end", "file", 0};
1585 static PyObject *dummy_args = NULL;
1586 static PyObject *unicode_newline = NULL, *unicode_space = NULL;
1587 static PyObject *str_newline = NULL, *str_space = NULL;
1588 PyObject *newline, *space;
1589 PyObject *sep = NULL, *end = NULL, *file = NULL;
1590 int i, err, use_unicode = 0;
Eric Smith7c478942008-03-18 23:45:49 +00001591
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001592 if (dummy_args == NULL) {
1593 if (!(dummy_args = PyTuple_New(0)))
1594 return NULL;
1595 }
1596 if (str_newline == NULL) {
1597 str_newline = PyString_FromString("\n");
1598 if (str_newline == NULL)
1599 return NULL;
1600 str_space = PyString_FromString(" ");
1601 if (str_space == NULL) {
1602 Py_CLEAR(str_newline);
1603 return NULL;
1604 }
Martin v. Löwised11a5d2012-05-20 10:42:17 +02001605#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001606 unicode_newline = PyUnicode_FromString("\n");
1607 if (unicode_newline == NULL) {
1608 Py_CLEAR(str_newline);
1609 Py_CLEAR(str_space);
1610 return NULL;
1611 }
1612 unicode_space = PyUnicode_FromString(" ");
1613 if (unicode_space == NULL) {
1614 Py_CLEAR(str_newline);
1615 Py_CLEAR(str_space);
1616 Py_CLEAR(unicode_space);
1617 return NULL;
1618 }
Martin v. Löwised11a5d2012-05-20 10:42:17 +02001619#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001620 }
1621 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1622 kwlist, &sep, &end, &file))
1623 return NULL;
1624 if (file == NULL || file == Py_None) {
1625 file = PySys_GetObject("stdout");
1626 /* sys.stdout may be None when FILE* stdout isn't connected */
1627 if (file == Py_None)
1628 Py_RETURN_NONE;
1629 }
1630 if (sep == Py_None) {
1631 sep = NULL;
1632 }
1633 else if (sep) {
1634 if (PyUnicode_Check(sep)) {
1635 use_unicode = 1;
1636 }
1637 else if (!PyString_Check(sep)) {
1638 PyErr_Format(PyExc_TypeError,
1639 "sep must be None, str or unicode, not %.200s",
1640 sep->ob_type->tp_name);
1641 return NULL;
1642 }
1643 }
1644 if (end == Py_None)
1645 end = NULL;
1646 else if (end) {
1647 if (PyUnicode_Check(end)) {
1648 use_unicode = 1;
1649 }
1650 else if (!PyString_Check(end)) {
1651 PyErr_Format(PyExc_TypeError,
1652 "end must be None, str or unicode, not %.200s",
1653 end->ob_type->tp_name);
1654 return NULL;
1655 }
1656 }
Benjamin Peterson753d1622009-07-02 18:16:45 +00001657
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001658 if (!use_unicode) {
1659 for (i = 0; i < PyTuple_Size(args); i++) {
1660 if (PyUnicode_Check(PyTuple_GET_ITEM(args, i))) {
1661 use_unicode = 1;
1662 break;
1663 }
1664 }
1665 }
1666 if (use_unicode) {
1667 newline = unicode_newline;
1668 space = unicode_space;
1669 }
1670 else {
1671 newline = str_newline;
1672 space = str_space;
1673 }
Eric Smith7c478942008-03-18 23:45:49 +00001674
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001675 for (i = 0; i < PyTuple_Size(args); i++) {
1676 if (i > 0) {
1677 if (sep == NULL)
1678 err = PyFile_WriteObject(space, file,
1679 Py_PRINT_RAW);
1680 else
1681 err = PyFile_WriteObject(sep, file,
1682 Py_PRINT_RAW);
1683 if (err)
1684 return NULL;
1685 }
1686 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1687 Py_PRINT_RAW);
1688 if (err)
1689 return NULL;
1690 }
Eric Smith7c478942008-03-18 23:45:49 +00001691
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001692 if (end == NULL)
1693 err = PyFile_WriteObject(newline, file, Py_PRINT_RAW);
1694 else
1695 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1696 if (err)
1697 return NULL;
Eric Smith7c478942008-03-18 23:45:49 +00001698
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001699 Py_RETURN_NONE;
Eric Smith7c478942008-03-18 23:45:49 +00001700}
1701
1702PyDoc_STRVAR(print_doc,
1703"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
1704\n\
1705Prints the values to a stream, or to sys.stdout by default.\n\
1706Optional keyword arguments:\n\
1707file: a file-like object (stream); defaults to the current sys.stdout.\n\
1708sep: string inserted between values, default a space.\n\
1709end: string appended after the last value, default a newline.");
1710
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001711
1712/* Return number of items in range (lo, hi, step), when arguments are
1713 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1714 * & only if the true value is too large to fit in a signed long.
1715 * Arguments MUST return 1 with either PyInt_Check() or
1716 * PyLong_Check(). Return -1 when there is an error.
1717 */
1718static long
1719get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
1720{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001721 /* -------------------------------------------------------------
1722 Algorithm is equal to that of get_len_of_range(), but it operates
1723 on PyObjects (which are assumed to be PyLong or PyInt objects).
1724 ---------------------------------------------------------------*/
1725 long n;
1726 PyObject *diff = NULL;
1727 PyObject *one = NULL;
1728 PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
1729 /* holds sub-expression evaluations */
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001730
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001731 /* if (lo >= hi), return length of 0. */
1732 if (PyObject_Compare(lo, hi) >= 0)
1733 return 0;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001734
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001735 if ((one = PyLong_FromLong(1L)) == NULL)
1736 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001737
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001738 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
1739 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001740
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001741 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
1742 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001743
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001744 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
1745 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001746
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001747 if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
1748 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001749
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001750 n = PyLong_AsLong(tmp3);
1751 if (PyErr_Occurred()) { /* Check for Overflow */
1752 PyErr_Clear();
1753 goto Fail;
1754 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001755
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001756 Py_DECREF(tmp3);
1757 Py_DECREF(tmp2);
1758 Py_DECREF(diff);
1759 Py_DECREF(tmp1);
1760 Py_DECREF(one);
1761 return n;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001762
1763 Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001764 Py_XDECREF(tmp3);
1765 Py_XDECREF(tmp2);
1766 Py_XDECREF(diff);
1767 Py_XDECREF(tmp1);
1768 Py_XDECREF(one);
1769 return -1;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001770}
1771
Mark Dickinsona8d26682010-05-04 16:18:25 +00001772/* Helper function for handle_range_longs. If arg is int or long
1773 object, returns it with incremented reference count. If arg is
1774 float, raises type error. As a last resort, creates a new int by
1775 calling arg type's nb_int method if it is defined. Returns NULL
1776 and sets exception on error.
1777
1778 Returns a new reference to an int object. */
1779static PyObject *
1780get_range_long_argument(PyObject *arg, const char *name)
1781{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001782 PyObject *v;
1783 PyNumberMethods *nb;
1784 if (PyInt_Check(arg) || PyLong_Check(arg)) {
1785 Py_INCREF(arg);
1786 return arg;
1787 }
1788 if (PyFloat_Check(arg) ||
1789 (nb = Py_TYPE(arg)->tp_as_number) == NULL ||
1790 nb->nb_int == NULL) {
1791 PyErr_Format(PyExc_TypeError,
1792 "range() integer %s argument expected, got %s.",
1793 name, arg->ob_type->tp_name);
1794 return NULL;
1795 }
1796 v = nb->nb_int(arg);
1797 if (v == NULL)
1798 return NULL;
1799 if (PyInt_Check(v) || PyLong_Check(v))
1800 return v;
1801 Py_DECREF(v);
1802 PyErr_SetString(PyExc_TypeError,
1803 "__int__ should return int object");
1804 return NULL;
Mark Dickinsona8d26682010-05-04 16:18:25 +00001805}
1806
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001807/* An extension of builtin_range() that handles the case when PyLong
1808 * arguments are given. */
1809static PyObject *
Mark Dickinsonef9b4ab2010-05-04 16:19:06 +00001810handle_range_longs(PyObject *self, PyObject *args)
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001811{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001812 PyObject *ilow = NULL;
1813 PyObject *ihigh = NULL;
1814 PyObject *istep = NULL;
Tim Peters874e1f72003-04-13 22:13:08 +00001815
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001816 PyObject *low = NULL;
1817 PyObject *high = NULL;
1818 PyObject *step = NULL;
Mark Dickinsona8d26682010-05-04 16:18:25 +00001819
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001820 PyObject *curnum = NULL;
1821 PyObject *v = NULL;
1822 long bign;
1823 Py_ssize_t i, n;
1824 int cmp_result;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001825
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001826 PyObject *zero = PyLong_FromLong(0);
Tim Peters874e1f72003-04-13 22:13:08 +00001827
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001828 if (zero == NULL)
1829 return NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001830
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001831 if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
1832 Py_DECREF(zero);
1833 return NULL;
1834 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001835
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001836 /* Figure out which way we were called, supply defaults, and be
1837 * sure to incref everything so that the decrefs at the end
1838 * are correct. NB: ilow, ihigh and istep are borrowed references.
1839 */
1840 assert(ilow != NULL);
1841 if (ihigh == NULL) {
1842 /* only 1 arg -- it's the upper limit */
1843 ihigh = ilow;
1844 ilow = NULL;
1845 }
Mark Dickinsona8d26682010-05-04 16:18:25 +00001846
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001847 /* convert ihigh if necessary */
1848 assert(ihigh != NULL);
1849 high = get_range_long_argument(ihigh, "end");
1850 if (high == NULL)
1851 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001852
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001853 /* ihigh correct now; do ilow */
1854 if (ilow == NULL) {
1855 Py_INCREF(zero);
1856 low = zero;
1857 }
1858 else {
1859 low = get_range_long_argument(ilow, "start");
1860 if (low == NULL)
1861 goto Fail;
1862 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001863
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001864 /* ilow and ihigh correct now; do istep */
1865 if (istep == NULL)
1866 step = PyLong_FromLong(1);
1867 else
1868 step = get_range_long_argument(istep, "step");
1869 if (step == NULL)
1870 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001871
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001872 if (PyObject_Cmp(step, zero, &cmp_result) == -1)
1873 goto Fail;
Tim Peters874e1f72003-04-13 22:13:08 +00001874
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001875 if (cmp_result == 0) {
1876 PyErr_SetString(PyExc_ValueError,
1877 "range() step argument must not be zero");
1878 goto Fail;
1879 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001880
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001881 if (cmp_result > 0)
1882 bign = get_len_of_range_longs(low, high, step);
1883 else {
1884 PyObject *neg_step = PyNumber_Negative(step);
1885 if (neg_step == NULL)
1886 goto Fail;
1887 bign = get_len_of_range_longs(high, low, neg_step);
1888 Py_DECREF(neg_step);
1889 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001890
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001891 n = (Py_ssize_t)bign;
1892 if (bign < 0 || (long)n != bign) {
1893 PyErr_SetString(PyExc_OverflowError,
1894 "range() result has too many items");
1895 goto Fail;
1896 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001897
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001898 v = PyList_New(n);
1899 if (v == NULL)
1900 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001901
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001902 curnum = low;
1903 Py_INCREF(curnum);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001904
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001905 for (i = 0; i < n; i++) {
1906 PyObject *w = PyNumber_Long(curnum);
1907 PyObject *tmp_num;
1908 if (w == NULL)
1909 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001910
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001911 PyList_SET_ITEM(v, i, w);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001912
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001913 tmp_num = PyNumber_Add(curnum, step);
1914 if (tmp_num == NULL)
1915 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001916
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001917 Py_DECREF(curnum);
1918 curnum = tmp_num;
1919 }
1920 Py_DECREF(low);
1921 Py_DECREF(high);
1922 Py_DECREF(step);
1923 Py_DECREF(zero);
1924 Py_DECREF(curnum);
1925 return v;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001926
1927 Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001928 Py_XDECREF(low);
1929 Py_XDECREF(high);
1930 Py_XDECREF(step);
1931 Py_DECREF(zero);
1932 Py_XDECREF(curnum);
1933 Py_XDECREF(v);
1934 return NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001935}
1936
Guido van Rossum124eff01999-02-23 16:11:01 +00001937/* Return number of items in range/xrange (lo, hi, step). step > 0
1938 * required. Return a value < 0 if & only if the true value is too
1939 * large to fit in a signed long.
1940 */
1941static long
Thomas Wouterse28c2962000-07-23 22:21:32 +00001942get_len_of_range(long lo, long hi, long step)
Guido van Rossum124eff01999-02-23 16:11:01 +00001943{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001944 /* -------------------------------------------------------------
1945 If lo >= hi, the range is empty.
1946 Else if n values are in the range, the last one is
1947 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1948 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1949 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1950 the RHS is non-negative and so truncation is the same as the
1951 floor. Letting M be the largest positive long, the worst case
1952 for the RHS numerator is hi=M, lo=-M-1, and then
1953 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1954 precision to compute the RHS exactly.
1955 ---------------------------------------------------------------*/
1956 long n = 0;
1957 if (lo < hi) {
1958 unsigned long uhi = (unsigned long)hi;
1959 unsigned long ulo = (unsigned long)lo;
1960 unsigned long diff = uhi - ulo - 1;
1961 n = (long)(diff / (unsigned long)step + 1);
1962 }
1963 return n;
Guido van Rossum124eff01999-02-23 16:11:01 +00001964}
1965
Guido van Rossum79f25d91997-04-29 20:08:16 +00001966static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001967builtin_range(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001968{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001969 long ilow = 0, ihigh = 0, istep = 1;
1970 long bign;
1971 Py_ssize_t i, n;
Guido van Rossum124eff01999-02-23 16:11:01 +00001972
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001973 PyObject *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001974
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001975 if (PyTuple_Size(args) <= 1) {
1976 if (!PyArg_ParseTuple(args,
1977 "l;range() requires 1-3 int arguments",
1978 &ihigh)) {
1979 PyErr_Clear();
1980 return handle_range_longs(self, args);
1981 }
1982 }
1983 else {
1984 if (!PyArg_ParseTuple(args,
1985 "ll|l;range() requires 1-3 int arguments",
1986 &ilow, &ihigh, &istep)) {
1987 PyErr_Clear();
1988 return handle_range_longs(self, args);
1989 }
1990 }
1991 if (istep == 0) {
1992 PyErr_SetString(PyExc_ValueError,
1993 "range() step argument must not be zero");
1994 return NULL;
1995 }
1996 if (istep > 0)
1997 bign = get_len_of_range(ilow, ihigh, istep);
1998 else
1999 bign = get_len_of_range(ihigh, ilow, -istep);
2000 n = (Py_ssize_t)bign;
2001 if (bign < 0 || (long)n != bign) {
2002 PyErr_SetString(PyExc_OverflowError,
2003 "range() result has too many items");
2004 return NULL;
2005 }
2006 v = PyList_New(n);
2007 if (v == NULL)
2008 return NULL;
2009 for (i = 0; i < n; i++) {
2010 PyObject *w = PyInt_FromLong(ilow);
2011 if (w == NULL) {
2012 Py_DECREF(v);
2013 return NULL;
2014 }
2015 PyList_SET_ITEM(v, i, w);
2016 ilow += istep;
2017 }
2018 return v;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002019}
2020
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002021PyDoc_STRVAR(range_doc,
Chris Jerdonekad4b0002012-10-07 20:37:54 -07002022"range(stop) -> list of integers\n\
2023range(start, stop[, step]) -> list of integers\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002024\n\
2025Return a list containing an arithmetic progression of integers.\n\
2026range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
2027When step is given, it specifies the increment (or decrement).\n\
2028For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002029These are exactly the valid indices for a list of 4 elements.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002030
2031
Guido van Rossum79f25d91997-04-29 20:08:16 +00002032static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002033builtin_raw_input(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002034{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002035 PyObject *v = NULL;
2036 PyObject *fin = PySys_GetObject("stdin");
2037 PyObject *fout = PySys_GetObject("stdout");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002038
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002039 if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
2040 return NULL;
Martin v. Löwis31d2df52002-08-14 15:46:02 +00002041
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002042 if (fin == NULL) {
2043 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
2044 return NULL;
2045 }
2046 if (fout == NULL) {
2047 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
2048 return NULL;
2049 }
2050 if (PyFile_SoftSpace(fout, 0)) {
2051 if (PyFile_WriteString(" ", fout) != 0)
2052 return NULL;
2053 }
2054 if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
2055 && isatty(fileno(PyFile_AsFile(fin)))
2056 && isatty(fileno(PyFile_AsFile(fout)))) {
2057 PyObject *po;
2058 char *prompt;
2059 char *s;
2060 PyObject *result;
2061 if (v != NULL) {
2062 po = PyObject_Str(v);
2063 if (po == NULL)
2064 return NULL;
2065 prompt = PyString_AsString(po);
2066 if (prompt == NULL)
2067 return NULL;
2068 }
2069 else {
2070 po = NULL;
2071 prompt = "";
2072 }
2073 s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
2074 prompt);
2075 Py_XDECREF(po);
2076 if (s == NULL) {
2077 if (!PyErr_Occurred())
2078 PyErr_SetNone(PyExc_KeyboardInterrupt);
2079 return NULL;
2080 }
2081 if (*s == '\0') {
2082 PyErr_SetNone(PyExc_EOFError);
2083 result = NULL;
2084 }
2085 else { /* strip trailing '\n' */
2086 size_t len = strlen(s);
2087 if (len > PY_SSIZE_T_MAX) {
2088 PyErr_SetString(PyExc_OverflowError,
2089 "[raw_]input: input too long");
2090 result = NULL;
2091 }
2092 else {
2093 result = PyString_FromStringAndSize(s, len-1);
2094 }
2095 }
2096 PyMem_FREE(s);
2097 return result;
2098 }
2099 if (v != NULL) {
2100 if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
2101 return NULL;
2102 }
2103 return PyFile_GetLine(fin, -1);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002104}
2105
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002106PyDoc_STRVAR(raw_input_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002107"raw_input([prompt]) -> string\n\
2108\n\
2109Read a string from standard input. The trailing newline is stripped.\n\
2110If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
2111On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002112is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002113
2114
Guido van Rossum79f25d91997-04-29 20:08:16 +00002115static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002116builtin_reduce(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002117{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002118 static PyObject *functools_reduce = NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002119
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002120 if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
2121 "use functools.reduce()", 1) < 0)
2122 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +00002123
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002124 if (functools_reduce == NULL) {
2125 PyObject *functools = PyImport_ImportModule("functools");
2126 if (functools == NULL)
2127 return NULL;
2128 functools_reduce = PyObject_GetAttrString(functools, "reduce");
2129 Py_DECREF(functools);
2130 if (functools_reduce == NULL)
2131 return NULL;
2132 }
2133 return PyObject_Call(functools_reduce, args, NULL);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002134}
2135
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002136PyDoc_STRVAR(reduce_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002137"reduce(function, sequence[, initial]) -> value\n\
2138\n\
2139Apply a function of two arguments cumulatively to the items of a sequence,\n\
2140from left to right, so as to reduce the sequence to a single value.\n\
2141For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
2142((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
2143of the sequence in the calculation, and serves as a default when the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002144sequence is empty.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002145
2146
Guido van Rossum79f25d91997-04-29 20:08:16 +00002147static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002148builtin_reload(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002149{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002150 if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
2151 1) < 0)
2152 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +00002153
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002154 return PyImport_ReloadModule(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002155}
2156
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002157PyDoc_STRVAR(reload_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002158"reload(module) -> module\n\
2159\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002160Reload the module. The module must have been successfully imported before.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002161
2162
Guido van Rossum79f25d91997-04-29 20:08:16 +00002163static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002164builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00002165{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002166 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002167}
2168
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002169PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002170"repr(object) -> string\n\
2171\n\
2172Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002173For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002174
2175
Guido van Rossum79f25d91997-04-29 20:08:16 +00002176static PyObject *
Georg Brandlccadf842006-03-31 18:54:53 +00002177builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002178{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002179 double x;
2180 PyObject *o_ndigits = NULL;
2181 Py_ssize_t ndigits;
2182 static char *kwlist[] = {"number", "ndigits", 0};
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002183
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002184 if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|O:round",
2185 kwlist, &x, &o_ndigits))
2186 return NULL;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002187
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002188 if (o_ndigits == NULL) {
2189 /* second argument defaults to 0 */
2190 ndigits = 0;
2191 }
2192 else {
2193 /* interpret 2nd argument as a Py_ssize_t; clip on overflow */
2194 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
2195 if (ndigits == -1 && PyErr_Occurred())
2196 return NULL;
2197 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002198
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002199 /* nans, infinities and zeros round to themselves */
2200 if (!Py_IS_FINITE(x) || x == 0.0)
2201 return PyFloat_FromDouble(x);
Mark Dickinsonbce78372009-11-24 10:54:58 +00002202
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002203 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
2204 always rounds to itself. For ndigits < NDIGITS_MIN, x always
2205 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002206#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
2207#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002208 if (ndigits > NDIGITS_MAX)
2209 /* return x */
2210 return PyFloat_FromDouble(x);
2211 else if (ndigits < NDIGITS_MIN)
2212 /* return 0.0, but with sign of x */
2213 return PyFloat_FromDouble(0.0*x);
2214 else
2215 /* finite x, and ndigits is not unreasonably large */
2216 /* _Py_double_round is defined in floatobject.c */
2217 return _Py_double_round(x, (int)ndigits);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002218#undef NDIGITS_MAX
2219#undef NDIGITS_MIN
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002220}
2221
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002222PyDoc_STRVAR(round_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002223"round(number[, ndigits]) -> floating point number\n\
2224\n\
2225Round a number to a given precision in decimal digits (default 0 digits).\n\
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +00002226This always returns a floating point number. Precision may be negative.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002227
Raymond Hettinger64958a12003-12-17 20:43:33 +00002228static PyObject *
2229builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2230{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002231 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
2232 PyObject *callable;
2233 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
2234 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002235
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002236 /* args 1-4 should match listsort in Objects/listobject.c */
2237 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
2238 kwlist, &seq, &compare, &keyfunc, &reverse))
2239 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002240
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002241 newlist = PySequence_List(seq);
2242 if (newlist == NULL)
2243 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002244
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002245 callable = PyObject_GetAttrString(newlist, "sort");
2246 if (callable == NULL) {
2247 Py_DECREF(newlist);
2248 return NULL;
2249 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002250
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002251 newargs = PyTuple_GetSlice(args, 1, 4);
2252 if (newargs == NULL) {
2253 Py_DECREF(newlist);
2254 Py_DECREF(callable);
2255 return NULL;
2256 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00002257
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002258 v = PyObject_Call(callable, newargs, kwds);
2259 Py_DECREF(newargs);
2260 Py_DECREF(callable);
2261 if (v == NULL) {
2262 Py_DECREF(newlist);
2263 return NULL;
2264 }
2265 Py_DECREF(v);
2266 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002267}
2268
2269PyDoc_STRVAR(sorted_doc,
2270"sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002271
Guido van Rossum79f25d91997-04-29 20:08:16 +00002272static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002273builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002274{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002275 PyObject *v = NULL;
2276 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002277
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002278 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2279 return NULL;
2280 if (v == NULL) {
2281 d = PyEval_GetLocals();
2282 if (d == NULL) {
2283 if (!PyErr_Occurred())
2284 PyErr_SetString(PyExc_SystemError,
2285 "vars(): no locals!?");
2286 }
2287 else
2288 Py_INCREF(d);
2289 }
2290 else {
2291 d = PyObject_GetAttrString(v, "__dict__");
2292 if (d == NULL) {
2293 PyErr_SetString(PyExc_TypeError,
2294 "vars() argument must have __dict__ attribute");
2295 return NULL;
2296 }
2297 }
2298 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002299}
2300
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002301PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002302"vars([object]) -> dictionary\n\
2303\n\
2304Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002305With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002306
Alex Martellia70b1912003-04-22 08:12:33 +00002307
2308static PyObject*
2309builtin_sum(PyObject *self, PyObject *args)
2310{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002311 PyObject *seq;
2312 PyObject *result = NULL;
2313 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002314
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002315 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
2316 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002317
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002318 iter = PyObject_GetIter(seq);
2319 if (iter == NULL)
2320 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002321
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002322 if (result == NULL) {
2323 result = PyInt_FromLong(0);
2324 if (result == NULL) {
2325 Py_DECREF(iter);
2326 return NULL;
2327 }
2328 } else {
2329 /* reject string values for 'start' parameter */
2330 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
2331 PyErr_SetString(PyExc_TypeError,
2332 "sum() can't sum strings [use ''.join(seq) instead]");
2333 Py_DECREF(iter);
2334 return NULL;
2335 }
2336 Py_INCREF(result);
2337 }
Alex Martellia70b1912003-04-22 08:12:33 +00002338
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002339#ifndef SLOW_SUM
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002340 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2341 Assumes all inputs are the same type. If the assumption fails, default
2342 to the more general routine.
2343 */
2344 if (PyInt_CheckExact(result)) {
2345 long i_result = PyInt_AS_LONG(result);
2346 Py_DECREF(result);
2347 result = NULL;
2348 while(result == NULL) {
2349 item = PyIter_Next(iter);
2350 if (item == NULL) {
2351 Py_DECREF(iter);
2352 if (PyErr_Occurred())
2353 return NULL;
2354 return PyInt_FromLong(i_result);
2355 }
2356 if (PyInt_CheckExact(item)) {
2357 long b = PyInt_AS_LONG(item);
2358 long x = i_result + b;
2359 if ((x^i_result) >= 0 || (x^b) >= 0) {
2360 i_result = x;
2361 Py_DECREF(item);
2362 continue;
2363 }
2364 }
2365 /* Either overflowed or is not an int. Restore real objects and process normally */
2366 result = PyInt_FromLong(i_result);
2367 temp = PyNumber_Add(result, item);
2368 Py_DECREF(result);
2369 Py_DECREF(item);
2370 result = temp;
2371 if (result == NULL) {
2372 Py_DECREF(iter);
2373 return NULL;
2374 }
2375 }
2376 }
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002377
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002378 if (PyFloat_CheckExact(result)) {
2379 double f_result = PyFloat_AS_DOUBLE(result);
2380 Py_DECREF(result);
2381 result = NULL;
2382 while(result == NULL) {
2383 item = PyIter_Next(iter);
2384 if (item == NULL) {
2385 Py_DECREF(iter);
2386 if (PyErr_Occurred())
2387 return NULL;
2388 return PyFloat_FromDouble(f_result);
2389 }
2390 if (PyFloat_CheckExact(item)) {
2391 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2392 f_result += PyFloat_AS_DOUBLE(item);
2393 PyFPE_END_PROTECT(f_result)
2394 Py_DECREF(item);
2395 continue;
2396 }
2397 if (PyInt_CheckExact(item)) {
2398 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2399 f_result += (double)PyInt_AS_LONG(item);
2400 PyFPE_END_PROTECT(f_result)
2401 Py_DECREF(item);
2402 continue;
2403 }
2404 result = PyFloat_FromDouble(f_result);
2405 temp = PyNumber_Add(result, item);
2406 Py_DECREF(result);
2407 Py_DECREF(item);
2408 result = temp;
2409 if (result == NULL) {
2410 Py_DECREF(iter);
2411 return NULL;
2412 }
2413 }
2414 }
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002415#endif
2416
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002417 for(;;) {
2418 item = PyIter_Next(iter);
2419 if (item == NULL) {
2420 /* error, or end-of-sequence */
2421 if (PyErr_Occurred()) {
2422 Py_DECREF(result);
2423 result = NULL;
2424 }
2425 break;
2426 }
2427 /* It's tempting to use PyNumber_InPlaceAdd instead of
2428 PyNumber_Add here, to avoid quadratic running time
2429 when doing 'sum(list_of_lists, [])'. However, this
2430 would produce a change in behaviour: a snippet like
Mark Dickinson0e0e2152009-10-26 14:18:44 +00002431
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002432 empty = []
2433 sum([[x] for x in range(10)], empty)
Mark Dickinson0e0e2152009-10-26 14:18:44 +00002434
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002435 would change the value of empty. */
2436 temp = PyNumber_Add(result, item);
2437 Py_DECREF(result);
2438 Py_DECREF(item);
2439 result = temp;
2440 if (result == NULL)
2441 break;
2442 }
2443 Py_DECREF(iter);
2444 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002445}
2446
2447PyDoc_STRVAR(sum_doc,
Mariatta536209e2017-06-06 09:12:03 -07002448"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002449\n\
Mariatta536209e2017-06-06 09:12:03 -07002450Return the sum of an iterable or sequence of numbers (NOT strings)\n\
2451plus the value of 'start' (which defaults to 0). When the sequence is\n\
R David Murrayf7c85842013-07-10 16:23:15 -04002452empty, return start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002453
2454
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002455static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002456builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002457{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002458 PyObject *inst;
2459 PyObject *cls;
2460 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002461
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002462 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2463 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002464
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002465 retval = PyObject_IsInstance(inst, cls);
2466 if (retval < 0)
2467 return NULL;
2468 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002469}
2470
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002471PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002472"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002473\n\
2474Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002475With a type as second argument, return whether that is the object's type.\n\
2476The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002477isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002478
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002479
2480static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002481builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002482{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002483 PyObject *derived;
2484 PyObject *cls;
2485 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002486
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002487 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2488 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002489
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002490 retval = PyObject_IsSubclass(derived, cls);
2491 if (retval < 0)
2492 return NULL;
2493 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002494}
2495
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002496PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002497"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002498\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002499Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2500When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2501is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002502
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002503
Barry Warsawbd599b52000-08-03 15:45:29 +00002504static PyObject*
2505builtin_zip(PyObject *self, PyObject *args)
2506{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002507 PyObject *ret;
2508 const Py_ssize_t itemsize = PySequence_Length(args);
2509 Py_ssize_t i;
2510 PyObject *itlist; /* tuple of iterators */
2511 Py_ssize_t len; /* guess at result length */
Barry Warsawbd599b52000-08-03 15:45:29 +00002512
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002513 if (itemsize == 0)
2514 return PyList_New(0);
Raymond Hettingereaef6152003-08-02 07:42:57 +00002515
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002516 /* args must be a tuple */
2517 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002518
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002519 /* Guess at result length: the shortest of the input lengths.
2520 If some argument refuses to say, we refuse to guess too, lest
2521 an argument like xrange(sys.maxint) lead us astray.*/
2522 len = -1; /* unknown */
2523 for (i = 0; i < itemsize; ++i) {
2524 PyObject *item = PyTuple_GET_ITEM(args, i);
2525 Py_ssize_t thislen = _PyObject_LengthHint(item, -2);
2526 if (thislen < 0) {
2527 if (thislen == -1)
2528 return NULL;
2529 len = -1;
2530 break;
2531 }
2532 else if (len < 0 || thislen < len)
2533 len = thislen;
2534 }
Tim Peters67d687a2002-04-29 21:27:32 +00002535
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002536 /* allocate result list */
2537 if (len < 0)
2538 len = 10; /* arbitrary */
2539 if ((ret = PyList_New(len)) == NULL)
2540 return NULL;
Barry Warsawbd599b52000-08-03 15:45:29 +00002541
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002542 /* obtain iterators */
2543 itlist = PyTuple_New(itemsize);
2544 if (itlist == NULL)
2545 goto Fail_ret;
2546 for (i = 0; i < itemsize; ++i) {
2547 PyObject *item = PyTuple_GET_ITEM(args, i);
2548 PyObject *it = PyObject_GetIter(item);
2549 if (it == NULL) {
2550 if (PyErr_ExceptionMatches(PyExc_TypeError))
2551 PyErr_Format(PyExc_TypeError,
2552 "zip argument #%zd must support iteration",
2553 i+1);
2554 goto Fail_ret_itlist;
2555 }
2556 PyTuple_SET_ITEM(itlist, i, it);
2557 }
Barry Warsawbd599b52000-08-03 15:45:29 +00002558
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002559 /* build result into ret list */
2560 for (i = 0; ; ++i) {
2561 int j;
2562 PyObject *next = PyTuple_New(itemsize);
2563 if (!next)
2564 goto Fail_ret_itlist;
Tim Peters8572b4f2001-05-06 01:05:02 +00002565
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002566 for (j = 0; j < itemsize; j++) {
2567 PyObject *it = PyTuple_GET_ITEM(itlist, j);
2568 PyObject *item = PyIter_Next(it);
2569 if (!item) {
2570 if (PyErr_Occurred()) {
2571 Py_DECREF(ret);
2572 ret = NULL;
2573 }
2574 Py_DECREF(next);
2575 Py_DECREF(itlist);
2576 goto Done;
2577 }
2578 PyTuple_SET_ITEM(next, j, item);
2579 }
Tim Peters8572b4f2001-05-06 01:05:02 +00002580
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002581 if (i < len)
2582 PyList_SET_ITEM(ret, i, next);
2583 else {
2584 int status = PyList_Append(ret, next);
2585 Py_DECREF(next);
2586 ++len;
2587 if (status < 0)
2588 goto Fail_ret_itlist;
2589 }
2590 }
Tim Peters8572b4f2001-05-06 01:05:02 +00002591
Tim Peters67d687a2002-04-29 21:27:32 +00002592Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002593 if (ret != NULL && i < len) {
2594 /* The list is too big. */
2595 if (PyList_SetSlice(ret, i, len, NULL) < 0)
2596 return NULL;
2597 }
2598 return ret;
Tim Peters67d687a2002-04-29 21:27:32 +00002599
Tim Peters8572b4f2001-05-06 01:05:02 +00002600Fail_ret_itlist:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002601 Py_DECREF(itlist);
Tim Peters8572b4f2001-05-06 01:05:02 +00002602Fail_ret:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002603 Py_DECREF(ret);
2604 return NULL;
Barry Warsawbd599b52000-08-03 15:45:29 +00002605}
2606
2607
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002608PyDoc_STRVAR(zip_doc,
Barry Warsawbd599b52000-08-03 15:45:29 +00002609"zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2610\n\
2611Return a list of tuples, where each tuple contains the i-th element\n\
2612from each of the argument sequences. The returned list is truncated\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002613in length to the length of the shortest argument sequence.");
Barry Warsawbd599b52000-08-03 15:45:29 +00002614
2615
Guido van Rossum79f25d91997-04-29 20:08:16 +00002616static PyMethodDef builtin_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002617 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2618 {"abs", builtin_abs, METH_O, abs_doc},
2619 {"all", builtin_all, METH_O, all_doc},
2620 {"any", builtin_any, METH_O, any_doc},
2621 {"apply", builtin_apply, METH_VARARGS, apply_doc},
2622 {"bin", builtin_bin, METH_O, bin_doc},
2623 {"callable", builtin_callable, METH_O, callable_doc},
2624 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2625 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
2626 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
2627 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2628 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2629 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2630 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2631 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2632 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
2633 {"filter", builtin_filter, METH_VARARGS, filter_doc},
2634 {"format", builtin_format, METH_VARARGS, format_doc},
2635 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2636 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2637 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2638 {"hash", builtin_hash, METH_O, hash_doc},
2639 {"hex", builtin_hex, METH_O, hex_doc},
2640 {"id", builtin_id, METH_O, id_doc},
2641 {"input", builtin_input, METH_VARARGS, input_doc},
2642 {"intern", builtin_intern, METH_VARARGS, intern_doc},
2643 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2644 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2645 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2646 {"len", builtin_len, METH_O, len_doc},
2647 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2648 {"map", builtin_map, METH_VARARGS, map_doc},
2649 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2650 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2651 {"next", builtin_next, METH_VARARGS, next_doc},
2652 {"oct", builtin_oct, METH_O, oct_doc},
2653 {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
2654 {"ord", builtin_ord, METH_O, ord_doc},
2655 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2656 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2657 {"range", builtin_range, METH_VARARGS, range_doc},
2658 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
2659 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
2660 {"reload", builtin_reload, METH_O, reload_doc},
2661 {"repr", builtin_repr, METH_O, repr_doc},
2662 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2663 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2664 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2665 {"sum", builtin_sum, METH_VARARGS, sum_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002666#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002667 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002668#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002669 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2670 {"zip", builtin_zip, METH_VARARGS, zip_doc},
2671 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002672};
2673
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002674PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002675"Built-in functions, exceptions, and other objects.\n\
2676\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002677Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002678
Guido van Rossum25ce5661997-08-02 03:10:38 +00002679PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002680_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002681{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002682 PyObject *mod, *dict, *debug;
2683 mod = Py_InitModule4("__builtin__", builtin_methods,
2684 builtin_doc, (PyObject *)NULL,
2685 PYTHON_API_VERSION);
2686 if (mod == NULL)
2687 return NULL;
2688 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002689
Tim Peters7571a0f2003-03-23 17:52:28 +00002690#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002691 /* __builtin__ exposes a number of statically allocated objects
2692 * that, before this code was added in 2.3, never showed up in
2693 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2694 * result, programs leaking references to None and False (etc)
2695 * couldn't be diagnosed by examining sys.getobjects(0).
2696 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002697#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2698#else
2699#define ADD_TO_ALL(OBJECT) (void)0
2700#endif
2701
Tim Peters4b7625e2001-09-13 21:37:17 +00002702#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002703 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2704 return NULL; \
2705 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002706
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002707 SETBUILTIN("None", Py_None);
2708 SETBUILTIN("Ellipsis", Py_Ellipsis);
2709 SETBUILTIN("NotImplemented", Py_NotImplemented);
2710 SETBUILTIN("False", Py_False);
2711 SETBUILTIN("True", Py_True);
2712 SETBUILTIN("basestring", &PyBaseString_Type);
2713 SETBUILTIN("bool", &PyBool_Type);
2714 SETBUILTIN("memoryview", &PyMemoryView_Type);
2715 SETBUILTIN("bytearray", &PyByteArray_Type);
2716 SETBUILTIN("bytes", &PyString_Type);
2717 SETBUILTIN("buffer", &PyBuffer_Type);
2718 SETBUILTIN("classmethod", &PyClassMethod_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002719#ifndef WITHOUT_COMPLEX
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002720 SETBUILTIN("complex", &PyComplex_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002721#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002722 SETBUILTIN("dict", &PyDict_Type);
2723 SETBUILTIN("enumerate", &PyEnum_Type);
2724 SETBUILTIN("file", &PyFile_Type);
2725 SETBUILTIN("float", &PyFloat_Type);
2726 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2727 SETBUILTIN("property", &PyProperty_Type);
2728 SETBUILTIN("int", &PyInt_Type);
2729 SETBUILTIN("list", &PyList_Type);
2730 SETBUILTIN("long", &PyLong_Type);
2731 SETBUILTIN("object", &PyBaseObject_Type);
2732 SETBUILTIN("reversed", &PyReversed_Type);
2733 SETBUILTIN("set", &PySet_Type);
2734 SETBUILTIN("slice", &PySlice_Type);
2735 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2736 SETBUILTIN("str", &PyString_Type);
2737 SETBUILTIN("super", &PySuper_Type);
2738 SETBUILTIN("tuple", &PyTuple_Type);
2739 SETBUILTIN("type", &PyType_Type);
2740 SETBUILTIN("xrange", &PyRange_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002741#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002742 SETBUILTIN("unicode", &PyUnicode_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002743#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002744 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2745 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2746 Py_XDECREF(debug);
2747 return NULL;
2748 }
2749 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002750
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002751 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002752#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002753#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002754}
2755
Guido van Rossume77a7571993-11-03 15:01:26 +00002756/* Helper for filter(): filter a tuple through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002757
Guido van Rossum79f25d91997-04-29 20:08:16 +00002758static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002759filtertuple(PyObject *func, PyObject *tuple)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002760{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002761 PyObject *result;
2762 Py_ssize_t i, j;
2763 Py_ssize_t len = PyTuple_Size(tuple);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002764
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002765 if (len == 0) {
2766 if (PyTuple_CheckExact(tuple))
2767 Py_INCREF(tuple);
2768 else
2769 tuple = PyTuple_New(0);
2770 return tuple;
2771 }
Guido van Rossumb7b45621995-08-04 04:07:45 +00002772
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002773 if ((result = PyTuple_New(len)) == NULL)
2774 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002775
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002776 for (i = j = 0; i < len; ++i) {
2777 PyObject *item, *good;
2778 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002779
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002780 if (tuple->ob_type->tp_as_sequence &&
2781 tuple->ob_type->tp_as_sequence->sq_item) {
2782 item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
2783 if (item == NULL)
2784 goto Fail_1;
2785 } else {
2786 PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
2787 goto Fail_1;
2788 }
2789 if (func == Py_None) {
2790 Py_INCREF(item);
2791 good = item;
2792 }
2793 else {
2794 PyObject *arg = PyTuple_Pack(1, item);
2795 if (arg == NULL) {
2796 Py_DECREF(item);
2797 goto Fail_1;
2798 }
2799 good = PyEval_CallObject(func, arg);
2800 Py_DECREF(arg);
2801 if (good == NULL) {
2802 Py_DECREF(item);
2803 goto Fail_1;
2804 }
2805 }
2806 ok = PyObject_IsTrue(good);
2807 Py_DECREF(good);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002808 if (ok > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002809 if (PyTuple_SetItem(result, j++, item) < 0)
2810 goto Fail_1;
2811 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002812 else {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002813 Py_DECREF(item);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002814 if (ok < 0)
2815 goto Fail_1;
2816 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002817 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002818
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002819 if (_PyTuple_Resize(&result, j) < 0)
2820 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002821
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002822 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002823
Guido van Rossum12d12c51993-10-26 17:58:25 +00002824Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002825 Py_DECREF(result);
2826 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002827}
2828
2829
Guido van Rossume77a7571993-11-03 15:01:26 +00002830/* Helper for filter(): filter a string through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002831
Guido van Rossum79f25d91997-04-29 20:08:16 +00002832static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002833filterstring(PyObject *func, PyObject *strobj)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002834{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002835 PyObject *result;
2836 Py_ssize_t i, j;
2837 Py_ssize_t len = PyString_Size(strobj);
2838 Py_ssize_t outlen = len;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002839
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002840 if (func == Py_None) {
2841 /* If it's a real string we can return the original,
2842 * as no character is ever false and __getitem__
2843 * does return this character. If it's a subclass
2844 * we must go through the __getitem__ loop */
2845 if (PyString_CheckExact(strobj)) {
2846 Py_INCREF(strobj);
2847 return strobj;
2848 }
2849 }
2850 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2851 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002852
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002853 for (i = j = 0; i < len; ++i) {
2854 PyObject *item;
2855 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002856
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002857 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2858 if (item == NULL)
2859 goto Fail_1;
2860 if (func==Py_None) {
2861 ok = 1;
2862 } else {
2863 PyObject *arg, *good;
2864 arg = PyTuple_Pack(1, item);
2865 if (arg == NULL) {
2866 Py_DECREF(item);
2867 goto Fail_1;
2868 }
2869 good = PyEval_CallObject(func, arg);
2870 Py_DECREF(arg);
2871 if (good == NULL) {
2872 Py_DECREF(item);
2873 goto Fail_1;
2874 }
2875 ok = PyObject_IsTrue(good);
2876 Py_DECREF(good);
2877 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002878 if (ok > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002879 Py_ssize_t reslen;
2880 if (!PyString_Check(item)) {
2881 PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
2882 " __getitem__ returned different type");
2883 Py_DECREF(item);
2884 goto Fail_1;
2885 }
2886 reslen = PyString_GET_SIZE(item);
2887 if (reslen == 1) {
2888 PyString_AS_STRING(result)[j++] =
2889 PyString_AS_STRING(item)[0];
2890 } else {
2891 /* do we need more space? */
2892 Py_ssize_t need = j;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002893
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002894 /* calculate space requirements while checking for overflow */
2895 if (need > PY_SSIZE_T_MAX - reslen) {
2896 Py_DECREF(item);
2897 goto Fail_1;
2898 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002899
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002900 need += reslen;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002901
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002902 if (need > PY_SSIZE_T_MAX - len) {
2903 Py_DECREF(item);
2904 goto Fail_1;
2905 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002906
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002907 need += len;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002908
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002909 if (need <= i) {
2910 Py_DECREF(item);
2911 goto Fail_1;
2912 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002913
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002914 need = need - i - 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002915
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002916 assert(need >= 0);
2917 assert(outlen >= 0);
Gregory P. Smith9d534572008-06-11 07:41:16 +00002918
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002919 if (need > outlen) {
2920 /* overallocate, to avoid reallocations */
2921 if (outlen > PY_SSIZE_T_MAX / 2) {
2922 Py_DECREF(item);
2923 return NULL;
2924 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002925
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002926 if (need<2*outlen) {
2927 need = 2*outlen;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002928 }
Martin Panterca56dd42016-09-17 07:54:55 +00002929 if (_PyString_Resize(&result, need)) {
2930 Py_DECREF(item);
2931 return NULL;
2932 }
2933 outlen = need;
2934 }
2935 memcpy(
2936 PyString_AS_STRING(result) + j,
2937 PyString_AS_STRING(item),
2938 reslen
2939 );
2940 j += reslen;
2941 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002942 }
2943 Py_DECREF(item);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002944 if (ok < 0)
2945 goto Fail_1;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002946 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002947
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002948 if (j < outlen)
2949 _PyString_Resize(&result, j);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002950
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002951 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002952
Guido van Rossum12d12c51993-10-26 17:58:25 +00002953Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002954 Py_DECREF(result);
2955 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002956}
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002957
2958#ifdef Py_USING_UNICODE
2959/* Helper for filter(): filter a Unicode object through a function */
2960
2961static PyObject *
2962filterunicode(PyObject *func, PyObject *strobj)
2963{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002964 PyObject *result;
2965 register Py_ssize_t i, j;
2966 Py_ssize_t len = PyUnicode_GetSize(strobj);
2967 Py_ssize_t outlen = len;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002968
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002969 if (func == Py_None) {
2970 /* If it's a real string we can return the original,
2971 * as no character is ever false and __getitem__
2972 * does return this character. If it's a subclass
2973 * we must go through the __getitem__ loop */
2974 if (PyUnicode_CheckExact(strobj)) {
2975 Py_INCREF(strobj);
2976 return strobj;
2977 }
2978 }
2979 if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
2980 return NULL;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002981
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002982 for (i = j = 0; i < len; ++i) {
2983 PyObject *item, *arg, *good;
2984 int ok;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002985
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002986 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2987 if (item == NULL)
2988 goto Fail_1;
2989 if (func == Py_None) {
2990 ok = 1;
2991 } else {
2992 arg = PyTuple_Pack(1, item);
2993 if (arg == NULL) {
2994 Py_DECREF(item);
2995 goto Fail_1;
2996 }
2997 good = PyEval_CallObject(func, arg);
2998 Py_DECREF(arg);
2999 if (good == NULL) {
3000 Py_DECREF(item);
3001 goto Fail_1;
3002 }
3003 ok = PyObject_IsTrue(good);
3004 Py_DECREF(good);
3005 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +02003006 if (ok > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003007 Py_ssize_t reslen;
3008 if (!PyUnicode_Check(item)) {
3009 PyErr_SetString(PyExc_TypeError,
3010 "can't filter unicode to unicode:"
3011 " __getitem__ returned different type");
3012 Py_DECREF(item);
3013 goto Fail_1;
3014 }
3015 reslen = PyUnicode_GET_SIZE(item);
3016 if (reslen == 1)
3017 PyUnicode_AS_UNICODE(result)[j++] =
3018 PyUnicode_AS_UNICODE(item)[0];
3019 else {
3020 /* do we need more space? */
3021 Py_ssize_t need = j + reslen + len - i - 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003022
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003023 /* check that didnt overflow */
3024 if ((j > PY_SSIZE_T_MAX - reslen) ||
3025 ((j + reslen) > PY_SSIZE_T_MAX - len) ||
3026 ((j + reslen + len) < i) ||
3027 ((j + reslen + len - i) <= 0)) {
3028 Py_DECREF(item);
3029 return NULL;
3030 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00003031
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003032 assert(need >= 0);
3033 assert(outlen >= 0);
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003034
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003035 if (need > outlen) {
Martin Panterca56dd42016-09-17 07:54:55 +00003036 /* overallocate, to avoid reallocations */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003037 if (need < 2 * outlen) {
Martin Panterca56dd42016-09-17 07:54:55 +00003038 if (outlen > PY_SSIZE_T_MAX / 2) {
3039 Py_DECREF(item);
3040 return NULL;
3041 } else {
3042 need = 2 * outlen;
3043 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003044 }
Martin Panterca56dd42016-09-17 07:54:55 +00003045
3046 if (PyUnicode_Resize(&result, need) < 0) {
3047 Py_DECREF(item);
3048 goto Fail_1;
3049 }
3050 outlen = need;
3051 }
3052 memcpy(PyUnicode_AS_UNICODE(result) + j,
3053 PyUnicode_AS_UNICODE(item),
3054 reslen*sizeof(Py_UNICODE));
3055 j += reslen;
3056 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003057 }
3058 Py_DECREF(item);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02003059 if (ok < 0)
3060 goto Fail_1;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003061 }
3062
3063 if (j < outlen)
3064 PyUnicode_Resize(&result, j);
3065
3066 return result;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003067
3068Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003069 Py_DECREF(result);
3070 return NULL;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003071}
3072#endif