blob: 4b819da8b39948846e35dadb7459de57a19f8610 [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\
Mariatta9b7b3a62018-02-02 11:23:53 -050057interpreter and not for general use, it is better to use\n\
R David Murray59488d22012-07-18 19:44:08 -040058importlib.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\
Mariatta9b7b3a62018-02-02 11:23:53 -050066fromlist is not empty. The level argument is used to determine whether to\n\
67perform absolute or relative imports: 0 is absolute, while a positive number\n\
Neal Norwitz92e212f2006-04-03 04:48:37 +000068is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000069
Guido van Rossum1ae940a1995-01-02 19:04:15 +000070
Guido van Rossum79f25d91997-04-29 20:08:16 +000071static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000072builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +000073{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000074 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +000075}
76
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000077PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000078"abs(number) -> number\n\
79\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000080Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000081
Raymond Hettinger96229b12005-03-11 06:49:40 +000082static PyObject *
83builtin_all(PyObject *self, PyObject *v)
84{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000085 PyObject *it, *item;
86 PyObject *(*iternext)(PyObject *);
87 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +000088
Antoine Pitrouc83ea132010-05-09 14:46:46 +000089 it = PyObject_GetIter(v);
90 if (it == NULL)
91 return NULL;
92 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +000093
Antoine Pitrouc83ea132010-05-09 14:46:46 +000094 for (;;) {
95 item = iternext(it);
96 if (item == NULL)
97 break;
98 cmp = PyObject_IsTrue(item);
99 Py_DECREF(item);
100 if (cmp < 0) {
101 Py_DECREF(it);
102 return NULL;
103 }
104 if (cmp == 0) {
105 Py_DECREF(it);
106 Py_RETURN_FALSE;
107 }
108 }
109 Py_DECREF(it);
110 if (PyErr_Occurred()) {
111 if (PyErr_ExceptionMatches(PyExc_StopIteration))
112 PyErr_Clear();
113 else
114 return NULL;
115 }
116 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000117}
118
119PyDoc_STRVAR(all_doc,
120"all(iterable) -> bool\n\
121\n\
Ezio Melotti94bf6972013-02-15 23:35:14 +0200122Return True if bool(x) is True for all values x in the iterable.\n\
123If the iterable is empty, return True.");
Raymond Hettinger96229b12005-03-11 06:49:40 +0000124
125static PyObject *
126builtin_any(PyObject *self, PyObject *v)
127{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000128 PyObject *it, *item;
129 PyObject *(*iternext)(PyObject *);
130 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000131
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000132 it = PyObject_GetIter(v);
133 if (it == NULL)
134 return NULL;
135 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000136
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000137 for (;;) {
138 item = iternext(it);
139 if (item == NULL)
140 break;
141 cmp = PyObject_IsTrue(item);
142 Py_DECREF(item);
143 if (cmp < 0) {
144 Py_DECREF(it);
145 return NULL;
146 }
147 if (cmp == 1) {
148 Py_DECREF(it);
149 Py_RETURN_TRUE;
150 }
151 }
152 Py_DECREF(it);
153 if (PyErr_Occurred()) {
154 if (PyErr_ExceptionMatches(PyExc_StopIteration))
155 PyErr_Clear();
156 else
157 return NULL;
158 }
159 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000160}
161
162PyDoc_STRVAR(any_doc,
163"any(iterable) -> bool\n\
164\n\
Ezio Melotti94bf6972013-02-15 23:35:14 +0200165Return True if bool(x) is True for any x in the iterable.\n\
166If the iterable is empty, return False.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000167
Guido van Rossum79f25d91997-04-29 20:08:16 +0000168static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000169builtin_apply(PyObject *self, PyObject *args)
Guido van Rossumc02e15c1991-12-16 13:03:00 +0000170{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000171 PyObject *func, *alist = NULL, *kwdict = NULL;
172 PyObject *t = NULL, *retval = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000173
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000174 if (PyErr_WarnPy3k("apply() not supported in 3.x; "
175 "use func(*args, **kwargs)", 1) < 0)
176 return NULL;
Neal Norwitz8b2bfbc2007-05-23 06:35:32 +0000177
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000178 if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))
179 return NULL;
180 if (alist != NULL) {
181 if (!PyTuple_Check(alist)) {
182 if (!PySequence_Check(alist)) {
183 PyErr_Format(PyExc_TypeError,
184 "apply() arg 2 expected sequence, found %s",
185 alist->ob_type->tp_name);
186 return NULL;
187 }
188 t = PySequence_Tuple(alist);
189 if (t == NULL)
190 return NULL;
191 alist = t;
192 }
193 }
194 if (kwdict != NULL && !PyDict_Check(kwdict)) {
195 PyErr_Format(PyExc_TypeError,
196 "apply() arg 3 expected dictionary, found %s",
197 kwdict->ob_type->tp_name);
198 goto finally;
199 }
200 retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
Barry Warsaw968f8cb1998-10-01 15:33:12 +0000201 finally:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000202 Py_XDECREF(t);
203 return retval;
Guido van Rossumc02e15c1991-12-16 13:03:00 +0000204}
205
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000206PyDoc_STRVAR(apply_doc,
Fred Drakef1fbc622001-01-12 17:05:05 +0000207"apply(object[, args[, kwargs]]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000208\n\
Fred Drake7b912121999-12-23 14:16:55 +0000209Call a callable object with positional arguments taken from the tuple args,\n\
210and keyword arguments taken from the optional dictionary kwargs.\n\
Raymond Hettingerff41c482003-04-06 09:01:11 +0000211Note that classes are callable, as are instances with a __call__() method.\n\
212\n\
213Deprecated since release 2.3. Instead, use the extended call syntax:\n\
214 function(*args, **keywords).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000215
216
Guido van Rossum79f25d91997-04-29 20:08:16 +0000217static PyObject *
Eric Smith3cd81942008-02-22 16:30:22 +0000218builtin_bin(PyObject *self, PyObject *v)
219{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000220 return PyNumber_ToBase(v, 2);
Eric Smith3cd81942008-02-22 16:30:22 +0000221}
222
223PyDoc_STRVAR(bin_doc,
224"bin(number) -> string\n\
225\n\
226Return the binary representation of an integer or long integer.");
227
228
229static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000230builtin_callable(PyObject *self, PyObject *v)
Guido van Rossum2d951851994-08-29 12:52:16 +0000231{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000232 return PyBool_FromLong((long)PyCallable_Check(v));
Guido van Rossum2d951851994-08-29 12:52:16 +0000233}
234
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000235PyDoc_STRVAR(callable_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000236"callable(object) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000237\n\
238Return whether the object is callable (i.e., some kind of function).\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000239Note that classes are callable, as are instances with a __call__() method.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000240
241
Guido van Rossum79f25d91997-04-29 20:08:16 +0000242static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000243builtin_filter(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000244{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000245 PyObject *func, *seq, *result, *it, *arg;
246 Py_ssize_t len; /* guess for result list size */
247 register Py_ssize_t j;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000248
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000249 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
250 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000251
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000252 /* Strings and tuples return a result of the same type. */
253 if (PyString_Check(seq))
254 return filterstring(func, seq);
Martin v. Löwis8afd7572003-01-25 22:46:11 +0000255#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000256 if (PyUnicode_Check(seq))
257 return filterunicode(func, seq);
Martin v. Löwis8afd7572003-01-25 22:46:11 +0000258#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000259 if (PyTuple_Check(seq))
260 return filtertuple(func, seq);
Tim Peters0e57abf2001-05-02 07:39:38 +0000261
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000262 /* Pre-allocate argument list tuple. */
263 arg = PyTuple_New(1);
264 if (arg == NULL)
265 return NULL;
Georg Brandle35b6572005-07-19 22:20:20 +0000266
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000267 /* Get iterator. */
268 it = PyObject_GetIter(seq);
269 if (it == NULL)
270 goto Fail_arg;
Tim Peters0e57abf2001-05-02 07:39:38 +0000271
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000272 /* Guess a result list size. */
273 len = _PyObject_LengthHint(seq, 8);
274 if (len == -1)
275 goto Fail_it;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000276
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000277 /* Get a result list. */
278 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
279 /* Eww - can modify the list in-place. */
280 Py_INCREF(seq);
281 result = seq;
282 }
283 else {
284 result = PyList_New(len);
285 if (result == NULL)
286 goto Fail_it;
287 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000288
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000289 /* Build the result list. */
290 j = 0;
291 for (;;) {
292 PyObject *item;
293 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000294
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000295 item = PyIter_Next(it);
296 if (item == NULL) {
297 if (PyErr_Occurred())
298 goto Fail_result_it;
299 break;
300 }
Guido van Rossumdc4b93d1993-10-27 14:56:44 +0000301
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000302 if (func == (PyObject *)&PyBool_Type || func == Py_None) {
303 ok = PyObject_IsTrue(item);
304 }
305 else {
306 PyObject *good;
307 PyTuple_SET_ITEM(arg, 0, item);
308 good = PyObject_Call(func, arg, NULL);
309 PyTuple_SET_ITEM(arg, 0, NULL);
310 if (good == NULL) {
311 Py_DECREF(item);
312 goto Fail_result_it;
313 }
314 ok = PyObject_IsTrue(good);
315 Py_DECREF(good);
316 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +0200317 if (ok > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000318 if (j < len)
319 PyList_SET_ITEM(result, j, item);
320 else {
321 int status = PyList_Append(result, item);
322 Py_DECREF(item);
323 if (status < 0)
324 goto Fail_result_it;
325 }
326 ++j;
327 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +0200328 else {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000329 Py_DECREF(item);
Antoine Pitrouc5bef752012-08-15 23:16:51 +0200330 if (ok < 0)
331 goto Fail_result_it;
332 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000333 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000334
Guido van Rossum12d12c51993-10-26 17:58:25 +0000335
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000336 /* Cut back result list if len is too big. */
337 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
338 goto Fail_result_it;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000339
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000340 Py_DECREF(it);
341 Py_DECREF(arg);
342 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000343
Tim Peters0e57abf2001-05-02 07:39:38 +0000344Fail_result_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000345 Py_DECREF(result);
Tim Peters0e57abf2001-05-02 07:39:38 +0000346Fail_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000347 Py_DECREF(it);
Guido van Rossumc7903a12002-08-16 07:04:56 +0000348Fail_arg:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000349 Py_DECREF(arg);
350 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000351}
352
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000353PyDoc_STRVAR(filter_doc,
Tim Petersd50e5442002-03-09 00:06:26 +0000354"filter(function or None, sequence) -> list, tuple, or string\n"
355"\n"
356"Return those items of sequence for which function(item) is true. If\n"
357"function is None, return the items that are true. If sequence is a tuple\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000358"or string, return the same type, else return a list.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000359
Guido van Rossum79f25d91997-04-29 20:08:16 +0000360static PyObject *
Eric Smitha9f7d622008-02-17 19:46:49 +0000361builtin_format(PyObject *self, PyObject *args)
362{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000363 PyObject *value;
364 PyObject *format_spec = NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +0000365
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000366 if (!PyArg_ParseTuple(args, "O|O:format", &value, &format_spec))
367 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +0000368
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000369 return PyObject_Format(value, format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +0000370}
371
372PyDoc_STRVAR(format_doc,
373"format(value[, format_spec]) -> string\n\
374\n\
375Returns value.__format__(format_spec)\n\
Serhiy Storchaka6ed7aff2017-09-11 09:26:39 +0300376format_spec defaults to the empty string.\n\
377See the Format Specification Mini-Language section of help('FORMATTING') for\n\
378details.");
Eric Smitha9f7d622008-02-17 19:46:49 +0000379
380static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000381builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000382{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000383 long x;
384 char s[1];
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000385
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000386 if (!PyArg_ParseTuple(args, "l:chr", &x))
387 return NULL;
388 if (x < 0 || x >= 256) {
389 PyErr_SetString(PyExc_ValueError,
390 "chr() arg not in range(256)");
391 return NULL;
392 }
393 s[0] = (char)x;
394 return PyString_FromStringAndSize(s, 1);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000395}
396
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000397PyDoc_STRVAR(chr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000398"chr(i) -> character\n\
399\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000400Return a string of one character with ordinal i; 0 <= i < 256.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000401
402
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000403#ifdef Py_USING_UNICODE
Guido van Rossum79f25d91997-04-29 20:08:16 +0000404static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000405builtin_unichr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000406{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000407 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000408
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000409 if (!PyArg_ParseTuple(args, "i:unichr", &x))
410 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000411
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000412 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000413}
414
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000415PyDoc_STRVAR(unichr_doc,
Fred Drake078b24f2000-04-13 02:42:50 +0000416"unichr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000417\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000418Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000419#endif
Guido van Rossum09095f32000-03-10 23:00:52 +0000420
421
422static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000423builtin_cmp(PyObject *self, PyObject *args)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000424{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000425 PyObject *a, *b;
426 int c;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000427
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000428 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
429 return NULL;
430 if (PyObject_Cmp(a, b, &c) < 0)
431 return NULL;
432 return PyInt_FromLong((long)c);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000433}
434
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000435PyDoc_STRVAR(cmp_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000436"cmp(x, y) -> integer\n\
437\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000438Return negative if x<y, zero if x==y, positive if x>y.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000439
440
Guido van Rossum79f25d91997-04-29 20:08:16 +0000441static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000442builtin_coerce(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000443{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000444 PyObject *v, *w;
445 PyObject *res;
Guido van Rossum5524a591995-01-10 15:26:20 +0000446
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000447 if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
448 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +0000449
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000450 if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
451 return NULL;
452 if (PyNumber_Coerce(&v, &w) < 0)
453 return NULL;
454 res = PyTuple_Pack(2, v, w);
455 Py_DECREF(v);
456 Py_DECREF(w);
457 return res;
Guido van Rossum04691fc1992-08-12 15:35:34 +0000458}
459
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000460PyDoc_STRVAR(coerce_doc,
Martin v. Löwis8d494f32004-08-25 10:42:41 +0000461"coerce(x, y) -> (x1, y1)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000462\n\
Martin v. Löwis8d494f32004-08-25 10:42:41 +0000463Return a tuple consisting of the two numeric arguments converted to\n\
464a common type, using the same rules as used by arithmetic operations.\n\
465If coercion is not possible, raise TypeError.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000466
Guido van Rossum79f25d91997-04-29 20:08:16 +0000467static PyObject *
Georg Brandl5240d742007-03-13 20:46:32 +0000468builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000469{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000470 char *str;
471 char *filename;
472 char *startstr;
473 int mode = -1;
474 int dont_inherit = 0;
475 int supplied_flags = 0;
476 int is_ast;
477 PyCompilerFlags cf;
478 PyObject *result = NULL, *cmd, *tmp = NULL;
479 Py_ssize_t length;
480 static char *kwlist[] = {"source", "filename", "mode", "flags",
481 "dont_inherit", NULL};
482 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000483
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000484 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
485 kwlist, &cmd, &filename, &startstr,
486 &supplied_flags, &dont_inherit))
487 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000488
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000489 cf.cf_flags = supplied_flags;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000490
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000491 if (supplied_flags &
492 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
493 {
494 PyErr_SetString(PyExc_ValueError,
495 "compile(): unrecognised flags");
496 return NULL;
497 }
498 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Georg Brandlfc8eef32008-03-28 12:11:56 +0000499
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000500 if (!dont_inherit) {
501 PyEval_MergeCompilerFlags(&cf);
502 }
Georg Brandlfc8eef32008-03-28 12:11:56 +0000503
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000504 if (strcmp(startstr, "exec") == 0)
505 mode = 0;
506 else if (strcmp(startstr, "eval") == 0)
507 mode = 1;
508 else if (strcmp(startstr, "single") == 0)
509 mode = 2;
510 else {
511 PyErr_SetString(PyExc_ValueError,
512 "compile() arg 3 must be 'exec', 'eval' or 'single'");
513 return NULL;
514 }
Georg Brandlf2bfd542008-03-29 13:24:23 +0000515
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000516 is_ast = PyAST_Check(cmd);
517 if (is_ast == -1)
518 return NULL;
519 if (is_ast) {
520 if (supplied_flags & PyCF_ONLY_AST) {
521 Py_INCREF(cmd);
522 result = cmd;
523 }
524 else {
525 PyArena *arena;
526 mod_ty mod;
Georg Brandlfc8eef32008-03-28 12:11:56 +0000527
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000528 arena = PyArena_New();
Stefan Kraha8857af2012-08-20 17:31:22 +0200529 if (arena == NULL)
530 return NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000531 mod = PyAST_obj2mod(cmd, arena, mode);
532 if (mod == NULL) {
533 PyArena_Free(arena);
534 return NULL;
535 }
536 result = (PyObject*)PyAST_Compile(mod, filename,
537 &cf, arena);
538 PyArena_Free(arena);
539 }
540 return result;
541 }
Serhiy Storchaka61565602015-11-20 21:56:21 +0200542 if (PyString_Check(cmd)) {
543 str = PyString_AS_STRING(cmd);
544 length = PyString_GET_SIZE(cmd);
545 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000546#ifdef Py_USING_UNICODE
Serhiy Storchaka61565602015-11-20 21:56:21 +0200547 else if (PyUnicode_Check(cmd)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000548 tmp = PyUnicode_AsUTF8String(cmd);
549 if (tmp == NULL)
550 return NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000551 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
Serhiy Storchaka61565602015-11-20 21:56:21 +0200552 str = PyString_AS_STRING(tmp);
553 length = PyString_GET_SIZE(tmp);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000554 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000555#endif
Serhiy Storchaka61565602015-11-20 21:56:21 +0200556 else if (!PyObject_AsReadBuffer(cmd, (const void **)&str, &length)) {
557 /* Copy to NUL-terminated buffer. */
558 tmp = PyString_FromStringAndSize(str, length);
559 if (tmp == NULL)
560 return NULL;
561 str = PyString_AS_STRING(tmp);
562 length = PyString_GET_SIZE(tmp);
563 }
564 else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000565 goto cleanup;
566 if ((size_t)length != strlen(str)) {
567 PyErr_SetString(PyExc_TypeError,
568 "compile() expected string without null bytes");
569 goto cleanup;
570 }
571 result = Py_CompileStringFlags(str, filename, start[mode], &cf);
Neal Norwitz3a9a3e72005-11-27 20:38:31 +0000572cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000573 Py_XDECREF(tmp);
574 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000575}
576
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000577PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000578"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000579\n\
580Compile the source string (a Python module, statement or expression)\n\
581into a code object that can be executed by the exec statement or eval().\n\
582The filename will be used for run-time error messages.\n\
583The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000584single (interactive) statement, or 'eval' to compile an expression.\n\
585The flags argument, if present, controls which future statements influence\n\
586the compilation of the code.\n\
587The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
588the effects of any future statements in effect in the code calling\n\
589compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000590in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000591
Guido van Rossum79f25d91997-04-29 20:08:16 +0000592static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000593builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000594{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000595 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000596
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000597 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
598 return NULL;
599 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000600}
601
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000602PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000603"dir([object]) -> list of strings\n"
604"\n"
Georg Brandl871f1bc2007-03-12 13:17:36 +0000605"If called without an argument, return the names in the current scope.\n"
606"Else, return an alphabetized list of names comprising (some of) the attributes\n"
607"of the given object, and of attributes reachable from it.\n"
608"If the object supplies a method named __dir__, it will be used; otherwise\n"
609"the default dir() logic is used and returns:\n"
610" for a module object: the module's attributes.\n"
611" for a class object: its attributes, and recursively the attributes\n"
612" of its bases.\n"
Georg Brandl3bb15672007-03-13 07:23:16 +0000613" for any other object: its attributes, its class's attributes, and\n"
Georg Brandl871f1bc2007-03-12 13:17:36 +0000614" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000615
Guido van Rossum79f25d91997-04-29 20:08:16 +0000616static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000617builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000618{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000619 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000620
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000621 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
622 return NULL;
623 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000624}
625
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000626PyDoc_STRVAR(divmod_doc,
Raymond Hettinger39540a02011-07-19 11:59:20 -0700627"divmod(x, y) -> (quotient, remainder)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000628\n\
Zachary Warefd583492016-04-28 14:38:48 -0500629Return the tuple (x//y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000630
631
Guido van Rossum79f25d91997-04-29 20:08:16 +0000632static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000633builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000634{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000635 PyObject *cmd, *result, *tmp = NULL;
636 PyObject *globals = Py_None, *locals = Py_None;
637 char *str;
638 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000639
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000640 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
641 return NULL;
642 if (locals != Py_None && !PyMapping_Check(locals)) {
643 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
644 return NULL;
645 }
646 if (globals != Py_None && !PyDict_Check(globals)) {
647 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
648 "globals must be a real dict; try eval(expr, {}, mapping)"
649 : "globals must be a dict");
650 return NULL;
651 }
652 if (globals == Py_None) {
653 globals = PyEval_GetGlobals();
654 if (locals == Py_None)
655 locals = PyEval_GetLocals();
656 }
657 else if (locals == Py_None)
658 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000659
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000660 if (globals == NULL || locals == NULL) {
661 PyErr_SetString(PyExc_TypeError,
662 "eval must be given globals and locals "
663 "when called without a frame");
664 return NULL;
665 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000666
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000667 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
668 if (PyDict_SetItemString(globals, "__builtins__",
669 PyEval_GetBuiltins()) != 0)
670 return NULL;
671 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000672
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000673 if (PyCode_Check(cmd)) {
674 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
675 PyErr_SetString(PyExc_TypeError,
676 "code object passed to eval() may not contain free variables");
677 return NULL;
678 }
679 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
680 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000681
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000682 if (!PyString_Check(cmd) &&
683 !PyUnicode_Check(cmd)) {
684 PyErr_SetString(PyExc_TypeError,
685 "eval() arg 1 must be a string or code object");
686 return NULL;
687 }
688 cf.cf_flags = 0;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000689
690#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000691 if (PyUnicode_Check(cmd)) {
692 tmp = PyUnicode_AsUTF8String(cmd);
693 if (tmp == NULL)
694 return NULL;
695 cmd = tmp;
696 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
697 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000698#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000699 if (PyString_AsStringAndSize(cmd, &str, NULL)) {
700 Py_XDECREF(tmp);
701 return NULL;
702 }
703 while (*str == ' ' || *str == '\t')
704 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000705
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000706 (void)PyEval_MergeCompilerFlags(&cf);
707 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
708 Py_XDECREF(tmp);
709 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000710}
711
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000712PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000713"eval(source[, globals[, locals]]) -> value\n\
714\n\
715Evaluate the source in the context of globals and locals.\n\
716The source may be a string representing a Python expression\n\
717or a code object as returned by compile().\n\
Neal Norwitz477ca1c2006-09-05 02:25:41 +0000718The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000719defaulting to the current globals and locals.\n\
720If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000721
722
Guido van Rossum79f25d91997-04-29 20:08:16 +0000723static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000724builtin_execfile(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000725{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000726 char *filename;
727 PyObject *globals = Py_None, *locals = Py_None;
728 PyObject *res;
729 FILE* fp = NULL;
730 PyCompilerFlags cf;
731 int exists;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000732
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000733 if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
734 1) < 0)
735 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +0000736
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000737 if (!PyArg_ParseTuple(args, "s|O!O:execfile",
738 &filename,
739 &PyDict_Type, &globals,
740 &locals))
741 return NULL;
742 if (locals != Py_None && !PyMapping_Check(locals)) {
743 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
744 return NULL;
745 }
746 if (globals == Py_None) {
747 globals = PyEval_GetGlobals();
748 if (locals == Py_None)
749 locals = PyEval_GetLocals();
750 }
751 else if (locals == Py_None)
752 locals = globals;
753 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
754 if (PyDict_SetItemString(globals, "__builtins__",
755 PyEval_GetBuiltins()) != 0)
756 return NULL;
757 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000758
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000759 exists = 0;
760 /* Test for existence or directory. */
Martin v. Löwis3484a182002-03-09 12:07:51 +0000761#if defined(PLAN9)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000762 {
763 Dir *d;
Martin v. Löwis3484a182002-03-09 12:07:51 +0000764
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000765 if ((d = dirstat(filename))!=nil) {
766 if(d->mode & DMDIR)
767 werrstr("is a directory");
768 else
769 exists = 1;
770 free(d);
771 }
772 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000773#elif defined(RISCOS)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000774 if (object_exists(filename)) {
775 if (isdir(filename))
776 errno = EISDIR;
777 else
778 exists = 1;
779 }
780#else /* standard Posix */
781 {
782 struct stat s;
783 if (stat(filename, &s) == 0) {
784 if (S_ISDIR(s.st_mode))
785# if defined(PYOS_OS2) && defined(PYCC_VACPP)
786 errno = EOS2ERR;
787# else
788 errno = EISDIR;
789# endif
790 else
791 exists = 1;
792 }
793 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000794#endif
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000795
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000796 if (exists) {
797 Py_BEGIN_ALLOW_THREADS
798 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
799 Py_END_ALLOW_THREADS
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000800
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000801 if (fp == NULL) {
802 exists = 0;
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000803 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000804 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000805
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000806 if (!exists) {
807 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
808 return NULL;
809 }
810 cf.cf_flags = 0;
811 if (PyEval_MergeCompilerFlags(&cf))
812 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
813 locals, 1, &cf);
814 else
815 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
816 locals, 1);
817 return res;
Guido van Rossum0f61f8a1992-02-25 18:55:05 +0000818}
819
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000820PyDoc_STRVAR(execfile_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000821"execfile(filename[, globals[, locals]])\n\
822\n\
823Read and execute a Python script from a file.\n\
824The globals and locals are dictionaries, defaulting to the current\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000825globals and locals. If only globals is given, locals defaults to it.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000826
827
Guido van Rossum79f25d91997-04-29 20:08:16 +0000828static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000829builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000830{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000831 PyObject *v, *result, *dflt = NULL;
832 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000833
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000834 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
835 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000836#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000837 if (PyUnicode_Check(name)) {
838 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
839 if (name == NULL)
840 return NULL;
841 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000842#endif
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000843
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000844 if (!PyString_Check(name)) {
845 PyErr_SetString(PyExc_TypeError,
846 "getattr(): attribute name must be string");
847 return NULL;
848 }
849 result = PyObject_GetAttr(v, name);
850 if (result == NULL && dflt != NULL &&
851 PyErr_ExceptionMatches(PyExc_AttributeError))
852 {
853 PyErr_Clear();
854 Py_INCREF(dflt);
855 result = dflt;
856 }
857 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000858}
859
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000860PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000861"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000862\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000863Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
864When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000865exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000866
867
Guido van Rossum79f25d91997-04-29 20:08:16 +0000868static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000869builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000870{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000871 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000872
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000873 d = PyEval_GetGlobals();
874 Py_XINCREF(d);
875 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000876}
877
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000878PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000879"globals() -> dictionary\n\
880\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000881Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000882
883
Guido van Rossum79f25d91997-04-29 20:08:16 +0000884static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000885builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000886{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000887 PyObject *v;
888 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000889
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000890 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
891 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000892#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000893 if (PyUnicode_Check(name)) {
894 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
895 if (name == NULL)
896 return NULL;
897 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000898#endif
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000899
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000900 if (!PyString_Check(name)) {
901 PyErr_SetString(PyExc_TypeError,
902 "hasattr(): attribute name must be string");
903 return NULL;
904 }
905 v = PyObject_GetAttr(v, name);
906 if (v == NULL) {
907 if (!PyErr_ExceptionMatches(PyExc_Exception))
908 return NULL;
909 else {
910 PyErr_Clear();
911 Py_INCREF(Py_False);
912 return Py_False;
913 }
914 }
915 Py_DECREF(v);
916 Py_INCREF(Py_True);
917 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000918}
919
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000920PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000921"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000922\n\
923Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000924(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000925
926
Guido van Rossum79f25d91997-04-29 20:08:16 +0000927static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000928builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000929{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000930 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000931}
932
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000933PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000934"id(object) -> integer\n\
935\n\
936Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000937simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000938
939
Guido van Rossum79f25d91997-04-29 20:08:16 +0000940static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000941builtin_map(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000942{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000943 typedef struct {
944 PyObject *it; /* the iterator object */
945 int saw_StopIteration; /* bool: did the iterator end? */
946 } sequence;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000947
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000948 PyObject *func, *result;
949 sequence *seqs = NULL, *sqp;
950 Py_ssize_t n, len;
951 register int i, j;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000952
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000953 n = PyTuple_Size(args);
954 if (n < 2) {
955 PyErr_SetString(PyExc_TypeError,
956 "map() requires at least two args");
957 return NULL;
958 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000959
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000960 func = PyTuple_GetItem(args, 0);
961 n--;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000962
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000963 if (func == Py_None) {
964 if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
965 "use list(...)", 1) < 0)
966 return NULL;
967 if (n == 1) {
968 /* map(None, S) is the same as list(S). */
969 return PySequence_List(PyTuple_GetItem(args, 1));
970 }
971 }
Guido van Rossumfa4ac711998-07-10 17:37:30 +0000972
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000973 /* Get space for sequence descriptors. Must NULL out the iterator
974 * pointers so that jumping to Fail_2 later doesn't see trash.
975 */
976 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
977 PyErr_NoMemory();
978 return NULL;
979 }
980 for (i = 0; i < n; ++i) {
981 seqs[i].it = (PyObject*)NULL;
982 seqs[i].saw_StopIteration = 0;
983 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000984
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000985 /* Do a first pass to obtain iterators for the arguments, and set len
986 * to the largest of their lengths.
987 */
988 len = 0;
989 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
990 PyObject *curseq;
991 Py_ssize_t curlen;
Guido van Rossumad991772001-01-12 16:03:05 +0000992
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000993 /* Get iterator. */
994 curseq = PyTuple_GetItem(args, i+1);
995 sqp->it = PyObject_GetIter(curseq);
996 if (sqp->it == NULL) {
997 static char errmsg[] =
998 "argument %d to map() must support iteration";
999 char errbuf[sizeof(errmsg) + 25];
1000 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
1001 PyErr_SetString(PyExc_TypeError, errbuf);
1002 goto Fail_2;
1003 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001004
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001005 /* Update len. */
1006 curlen = _PyObject_LengthHint(curseq, 8);
1007 if (curlen > len)
1008 len = curlen;
1009 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001010
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001011 /* Get space for the result list. */
1012 if ((result = (PyObject *) PyList_New(len)) == NULL)
1013 goto Fail_2;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001014
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001015 /* Iterate over the sequences until all have stopped. */
1016 for (i = 0; ; ++i) {
1017 PyObject *alist, *item=NULL, *value;
1018 int numactive = 0;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001019
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001020 if (func == Py_None && n == 1)
1021 alist = NULL;
1022 else if ((alist = PyTuple_New(n)) == NULL)
1023 goto Fail_1;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001024
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001025 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
1026 if (sqp->saw_StopIteration) {
1027 Py_INCREF(Py_None);
1028 item = Py_None;
1029 }
1030 else {
1031 item = PyIter_Next(sqp->it);
1032 if (item)
1033 ++numactive;
1034 else {
1035 if (PyErr_Occurred()) {
1036 Py_XDECREF(alist);
1037 goto Fail_1;
1038 }
1039 Py_INCREF(Py_None);
1040 item = Py_None;
1041 sqp->saw_StopIteration = 1;
1042 }
1043 }
1044 if (alist)
1045 PyTuple_SET_ITEM(alist, j, item);
1046 else
1047 break;
1048 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001049
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001050 if (!alist)
1051 alist = item;
Guido van Rossum2d951851994-08-29 12:52:16 +00001052
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001053 if (numactive == 0) {
1054 Py_DECREF(alist);
1055 break;
1056 }
Guido van Rossum2d951851994-08-29 12:52:16 +00001057
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001058 if (func == Py_None)
1059 value = alist;
1060 else {
1061 value = PyEval_CallObject(func, alist);
1062 Py_DECREF(alist);
1063 if (value == NULL)
1064 goto Fail_1;
1065 }
1066 if (i >= len) {
1067 int status = PyList_Append(result, value);
1068 Py_DECREF(value);
1069 if (status < 0)
1070 goto Fail_1;
1071 }
1072 else if (PyList_SetItem(result, i, value) < 0)
1073 goto Fail_1;
1074 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00001075
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001076 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
1077 goto Fail_1;
Guido van Rossumfa4ac711998-07-10 17:37:30 +00001078
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001079 goto Succeed;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001080
Guido van Rossum12d12c51993-10-26 17:58:25 +00001081Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001082 Py_DECREF(result);
Guido van Rossum12d12c51993-10-26 17:58:25 +00001083Fail_2:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001084 result = NULL;
Tim Peters4e9afdc2001-05-03 23:54:49 +00001085Succeed:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001086 assert(seqs);
1087 for (i = 0; i < n; ++i)
1088 Py_XDECREF(seqs[i].it);
1089 PyMem_DEL(seqs);
1090 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001091}
1092
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001093PyDoc_STRVAR(map_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001094"map(function, sequence[, sequence, ...]) -> list\n\
1095\n\
1096Return a list of the results of applying the function to the items of\n\
1097the argument sequence(s). If more than one sequence is given, the\n\
1098function is called with an argument list consisting of the corresponding\n\
1099item of each sequence, substituting None for missing values when not all\n\
1100sequences have the same length. If the function is None, return a list of\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001101the items of the sequence (or a list of tuples if more than one sequence).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001102
1103
Guido van Rossum79f25d91997-04-29 20:08:16 +00001104static PyObject *
Georg Brandl28e08732008-04-30 19:47:09 +00001105builtin_next(PyObject *self, PyObject *args)
1106{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001107 PyObject *it, *res;
1108 PyObject *def = NULL;
Georg Brandl28e08732008-04-30 19:47:09 +00001109
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001110 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1111 return NULL;
1112 if (!PyIter_Check(it)) {
1113 PyErr_Format(PyExc_TypeError,
1114 "%.200s object is not an iterator",
1115 it->ob_type->tp_name);
1116 return NULL;
1117 }
1118
1119 res = (*it->ob_type->tp_iternext)(it);
1120 if (res != NULL) {
1121 return res;
1122 } else if (def != NULL) {
1123 if (PyErr_Occurred()) {
1124 if (!PyErr_ExceptionMatches(PyExc_StopIteration))
1125 return NULL;
1126 PyErr_Clear();
1127 }
1128 Py_INCREF(def);
1129 return def;
1130 } else if (PyErr_Occurred()) {
1131 return NULL;
1132 } else {
1133 PyErr_SetNone(PyExc_StopIteration);
1134 return NULL;
1135 }
Georg Brandl28e08732008-04-30 19:47:09 +00001136}
1137
1138PyDoc_STRVAR(next_doc,
1139"next(iterator[, default])\n\
1140\n\
1141Return the next item from the iterator. If default is given and the iterator\n\
1142is exhausted, it is returned instead of raising StopIteration.");
1143
1144
1145static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001146builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001147{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001148 PyObject *v;
1149 PyObject *name;
1150 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001151
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001152 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1153 return NULL;
1154 if (PyObject_SetAttr(v, name, value) != 0)
1155 return NULL;
1156 Py_INCREF(Py_None);
1157 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001158}
1159
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001160PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001161"setattr(object, name, value)\n\
1162\n\
1163Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001164``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001165
1166
Guido van Rossum79f25d91997-04-29 20:08:16 +00001167static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001168builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001169{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001170 PyObject *v;
1171 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001172
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001173 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1174 return NULL;
1175 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1176 return NULL;
1177 Py_INCREF(Py_None);
1178 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001179}
1180
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001181PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001182"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001183\n\
1184Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001185``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001186
1187
Guido van Rossum79f25d91997-04-29 20:08:16 +00001188static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001189builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001190{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001191 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001192
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001193 x = PyObject_Hash(v);
1194 if (x == -1)
1195 return NULL;
1196 return PyInt_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001197}
1198
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001199PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001200"hash(object) -> integer\n\
1201\n\
1202Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001203the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001204
1205
Guido van Rossum79f25d91997-04-29 20:08:16 +00001206static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001207builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001208{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001209 PyNumberMethods *nb;
1210 PyObject *res;
Benjamin Petersonc6d64ec2008-05-17 20:09:42 +00001211
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001212 if ((nb = v->ob_type->tp_as_number) == NULL ||
1213 nb->nb_hex == NULL) {
1214 PyErr_SetString(PyExc_TypeError,
1215 "hex() argument can't be converted to hex");
1216 return NULL;
1217 }
1218 res = (*nb->nb_hex)(v);
1219 if (res && !PyString_Check(res)) {
1220 PyErr_Format(PyExc_TypeError,
1221 "__hex__ returned non-string (type %.200s)",
1222 res->ob_type->tp_name);
1223 Py_DECREF(res);
1224 return NULL;
1225 }
1226 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001227}
1228
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001229PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001230"hex(number) -> string\n\
1231\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001232Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001233
1234
Tim Petersdbd9ba62000-07-09 03:09:57 +00001235static PyObject *builtin_raw_input(PyObject *, PyObject *);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001236
Guido van Rossum79f25d91997-04-29 20:08:16 +00001237static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001238builtin_input(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001239{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001240 PyObject *line;
1241 char *str;
1242 PyObject *res;
1243 PyObject *globals, *locals;
1244 PyCompilerFlags cf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001245
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001246 line = builtin_raw_input(self, args);
1247 if (line == NULL)
1248 return line;
1249 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1250 return NULL;
1251 while (*str == ' ' || *str == '\t')
1252 str++;
1253 globals = PyEval_GetGlobals();
1254 locals = PyEval_GetLocals();
1255 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1256 if (PyDict_SetItemString(globals, "__builtins__",
1257 PyEval_GetBuiltins()) != 0)
1258 return NULL;
1259 }
1260 cf.cf_flags = 0;
1261 PyEval_MergeCompilerFlags(&cf);
1262 res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
1263 Py_DECREF(line);
1264 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001265}
1266
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001267PyDoc_STRVAR(input_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001268"input([prompt]) -> value\n\
1269\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001270Equivalent to eval(raw_input(prompt)).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001271
1272
Guido van Rossume8811f81997-02-14 15:48:05 +00001273static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001274builtin_intern(PyObject *self, PyObject *args)
Guido van Rossume8811f81997-02-14 15:48:05 +00001275{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001276 PyObject *s;
1277 if (!PyArg_ParseTuple(args, "S:intern", &s))
1278 return NULL;
1279 if (!PyString_CheckExact(s)) {
1280 PyErr_SetString(PyExc_TypeError,
1281 "can't intern subclass of string");
1282 return NULL;
1283 }
1284 Py_INCREF(s);
1285 PyString_InternInPlace(&s);
1286 return s;
Guido van Rossume8811f81997-02-14 15:48:05 +00001287}
1288
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001289PyDoc_STRVAR(intern_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001290"intern(string) -> string\n\
1291\n\
1292``Intern'' the given string. This enters the string in the (global)\n\
1293table of interned strings whose purpose is to speed up dictionary lookups.\n\
1294Return the string itself or the previously interned string object with the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001295same value.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001296
1297
Guido van Rossum79f25d91997-04-29 20:08:16 +00001298static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001299builtin_iter(PyObject *self, PyObject *args)
1300{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001301 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001302
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001303 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1304 return NULL;
1305 if (w == NULL)
1306 return PyObject_GetIter(v);
1307 if (!PyCallable_Check(v)) {
1308 PyErr_SetString(PyExc_TypeError,
1309 "iter(v, w): v must be callable");
1310 return NULL;
1311 }
1312 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001313}
1314
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001315PyDoc_STRVAR(iter_doc,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001316"iter(collection) -> iterator\n\
1317iter(callable, sentinel) -> iterator\n\
1318\n\
1319Get an iterator from an object. In the first form, the argument must\n\
1320supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001321In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001322
1323
1324static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001325builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001326{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001327 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001328
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001329 res = PyObject_Size(v);
1330 if (res < 0 && PyErr_Occurred())
1331 return NULL;
1332 return PyInt_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001333}
1334
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001335PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001336"len(object) -> integer\n\
1337\n\
Terry Jan Reedy9f2dcd22014-06-16 03:05:30 -04001338Return the number of items of a sequence or collection.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001339
1340
Guido van Rossum79f25d91997-04-29 20:08:16 +00001341static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001342builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001343{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001344 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001345
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001346 d = PyEval_GetLocals();
1347 Py_XINCREF(d);
1348 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001349}
1350
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001351PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001352"locals() -> dictionary\n\
1353\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001354Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001355
1356
Guido van Rossum79f25d91997-04-29 20:08:16 +00001357static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001358min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001359{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001360 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1361 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001362
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001363 if (PyTuple_Size(args) > 1)
1364 v = args;
1365 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1366 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001367
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001368 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1369 keyfunc = PyDict_GetItemString(kwds, "key");
1370 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1371 PyErr_Format(PyExc_TypeError,
1372 "%s() got an unexpected keyword argument", name);
1373 return NULL;
1374 }
1375 Py_INCREF(keyfunc);
1376 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001377
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001378 it = PyObject_GetIter(v);
1379 if (it == NULL) {
1380 Py_XDECREF(keyfunc);
1381 return NULL;
1382 }
Tim Petersc3074532001-05-03 07:00:32 +00001383
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001384 maxitem = NULL; /* the result */
1385 maxval = NULL; /* the value associated with the result */
1386 while (( item = PyIter_Next(it) )) {
1387 /* get the value from the key function */
1388 if (keyfunc != NULL) {
1389 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1390 if (val == NULL)
1391 goto Fail_it_item;
1392 }
1393 /* no key function; the value is the item */
1394 else {
1395 val = item;
1396 Py_INCREF(val);
1397 }
Tim Petersc3074532001-05-03 07:00:32 +00001398
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001399 /* maximum value and item are unset; set them */
1400 if (maxval == NULL) {
1401 maxitem = item;
1402 maxval = val;
1403 }
1404 /* maximum value and item are set; update them as necessary */
1405 else {
1406 int cmp = PyObject_RichCompareBool(val, maxval, op);
1407 if (cmp < 0)
1408 goto Fail_it_item_and_val;
1409 else if (cmp > 0) {
1410 Py_DECREF(maxval);
1411 Py_DECREF(maxitem);
1412 maxval = val;
1413 maxitem = item;
1414 }
1415 else {
1416 Py_DECREF(item);
1417 Py_DECREF(val);
1418 }
1419 }
1420 }
1421 if (PyErr_Occurred())
1422 goto Fail_it;
1423 if (maxval == NULL) {
1424 PyErr_Format(PyExc_ValueError,
1425 "%s() arg is an empty sequence", name);
1426 assert(maxitem == NULL);
1427 }
1428 else
1429 Py_DECREF(maxval);
1430 Py_DECREF(it);
1431 Py_XDECREF(keyfunc);
1432 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001433
1434Fail_it_item_and_val:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001435 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001436Fail_it_item:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001437 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001438Fail_it:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001439 Py_XDECREF(maxval);
1440 Py_XDECREF(maxitem);
1441 Py_DECREF(it);
1442 Py_XDECREF(keyfunc);
1443 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001444}
1445
Guido van Rossum79f25d91997-04-29 20:08:16 +00001446static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001447builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001448{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001449 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001450}
1451
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001452PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001453"min(iterable[, key=func]) -> value\n\
1454min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001455\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001456With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001457With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001458
1459
Guido van Rossum79f25d91997-04-29 20:08:16 +00001460static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001461builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001462{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001463 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001464}
1465
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001466PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001467"max(iterable[, key=func]) -> value\n\
1468max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001469\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001470With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001471With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001472
1473
Guido van Rossum79f25d91997-04-29 20:08:16 +00001474static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001475builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001476{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001477 PyNumberMethods *nb;
1478 PyObject *res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001479
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001480 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1481 nb->nb_oct == NULL) {
1482 PyErr_SetString(PyExc_TypeError,
1483 "oct() argument can't be converted to oct");
1484 return NULL;
1485 }
1486 res = (*nb->nb_oct)(v);
1487 if (res && !PyString_Check(res)) {
1488 PyErr_Format(PyExc_TypeError,
1489 "__oct__ returned non-string (type %.200s)",
1490 res->ob_type->tp_name);
1491 Py_DECREF(res);
1492 return NULL;
1493 }
1494 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001495}
1496
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001497PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001498"oct(number) -> string\n\
1499\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001500Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001501
1502
Guido van Rossum79f25d91997-04-29 20:08:16 +00001503static PyObject *
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001504builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
1505{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001506 return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001507}
1508
1509PyDoc_STRVAR(open_doc,
1510"open(name[, mode[, buffering]]) -> file object\n\
1511\n\
Skip Montanaro4e3ebe02007-12-08 14:37:43 +00001512Open a file using the file() type, returns a file object. This is the\n\
Philip Jenveydd0388a2009-05-28 03:12:16 +00001513preferred way to open a file. See file.__doc__ for further information.");
Neal Norwitzc4edb0e2006-05-02 04:43:14 +00001514
1515
1516static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001517builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001518{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001519 long ord;
1520 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001521
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001522 if (PyString_Check(obj)) {
1523 size = PyString_GET_SIZE(obj);
1524 if (size == 1) {
1525 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1526 return PyInt_FromLong(ord);
1527 }
1528 } else if (PyByteArray_Check(obj)) {
1529 size = PyByteArray_GET_SIZE(obj);
1530 if (size == 1) {
1531 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1532 return PyInt_FromLong(ord);
1533 }
Christian Heimes1a6387e2008-03-26 12:49:49 +00001534
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001535#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001536 } else if (PyUnicode_Check(obj)) {
1537 size = PyUnicode_GET_SIZE(obj);
1538 if (size == 1) {
1539 ord = (long)*PyUnicode_AS_UNICODE(obj);
1540 return PyInt_FromLong(ord);
1541 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001542#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001543 } else {
1544 PyErr_Format(PyExc_TypeError,
1545 "ord() expected string of length 1, but " \
1546 "%.200s found", obj->ob_type->tp_name);
1547 return NULL;
1548 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001549
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001550 PyErr_Format(PyExc_TypeError,
1551 "ord() expected a character, "
1552 "but string of length %zd found",
1553 size);
1554 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001555}
1556
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001557PyDoc_STRVAR(ord_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001558"ord(c) -> integer\n\
1559\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001560Return the integer ordinal of a one-character string.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001561
1562
Guido van Rossum79f25d91997-04-29 20:08:16 +00001563static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001564builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001565{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001566 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001567
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001568 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1569 return NULL;
1570 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001571}
1572
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001573PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001574"pow(x, y[, z]) -> number\n\
1575\n\
1576With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001577equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001578
1579
Eric Smith7c478942008-03-18 23:45:49 +00001580static PyObject *
1581builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1582{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001583 static char *kwlist[] = {"sep", "end", "file", 0};
1584 static PyObject *dummy_args = NULL;
1585 static PyObject *unicode_newline = NULL, *unicode_space = NULL;
1586 static PyObject *str_newline = NULL, *str_space = NULL;
1587 PyObject *newline, *space;
1588 PyObject *sep = NULL, *end = NULL, *file = NULL;
1589 int i, err, use_unicode = 0;
Eric Smith7c478942008-03-18 23:45:49 +00001590
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001591 if (dummy_args == NULL) {
1592 if (!(dummy_args = PyTuple_New(0)))
1593 return NULL;
1594 }
1595 if (str_newline == NULL) {
1596 str_newline = PyString_FromString("\n");
1597 if (str_newline == NULL)
1598 return NULL;
1599 str_space = PyString_FromString(" ");
1600 if (str_space == NULL) {
1601 Py_CLEAR(str_newline);
1602 return NULL;
1603 }
Martin v. Löwised11a5d2012-05-20 10:42:17 +02001604#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001605 unicode_newline = PyUnicode_FromString("\n");
1606 if (unicode_newline == NULL) {
1607 Py_CLEAR(str_newline);
1608 Py_CLEAR(str_space);
1609 return NULL;
1610 }
1611 unicode_space = PyUnicode_FromString(" ");
1612 if (unicode_space == NULL) {
1613 Py_CLEAR(str_newline);
1614 Py_CLEAR(str_space);
1615 Py_CLEAR(unicode_space);
1616 return NULL;
1617 }
Martin v. Löwised11a5d2012-05-20 10:42:17 +02001618#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001619 }
1620 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1621 kwlist, &sep, &end, &file))
1622 return NULL;
1623 if (file == NULL || file == Py_None) {
1624 file = PySys_GetObject("stdout");
1625 /* sys.stdout may be None when FILE* stdout isn't connected */
1626 if (file == Py_None)
1627 Py_RETURN_NONE;
1628 }
1629 if (sep == Py_None) {
1630 sep = NULL;
1631 }
1632 else if (sep) {
1633 if (PyUnicode_Check(sep)) {
1634 use_unicode = 1;
1635 }
1636 else if (!PyString_Check(sep)) {
1637 PyErr_Format(PyExc_TypeError,
1638 "sep must be None, str or unicode, not %.200s",
1639 sep->ob_type->tp_name);
1640 return NULL;
1641 }
1642 }
1643 if (end == Py_None)
1644 end = NULL;
1645 else if (end) {
1646 if (PyUnicode_Check(end)) {
1647 use_unicode = 1;
1648 }
1649 else if (!PyString_Check(end)) {
1650 PyErr_Format(PyExc_TypeError,
1651 "end must be None, str or unicode, not %.200s",
1652 end->ob_type->tp_name);
1653 return NULL;
1654 }
1655 }
Benjamin Peterson753d1622009-07-02 18:16:45 +00001656
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001657 if (!use_unicode) {
1658 for (i = 0; i < PyTuple_Size(args); i++) {
1659 if (PyUnicode_Check(PyTuple_GET_ITEM(args, i))) {
1660 use_unicode = 1;
1661 break;
1662 }
1663 }
1664 }
1665 if (use_unicode) {
1666 newline = unicode_newline;
1667 space = unicode_space;
1668 }
1669 else {
1670 newline = str_newline;
1671 space = str_space;
1672 }
Eric Smith7c478942008-03-18 23:45:49 +00001673
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001674 for (i = 0; i < PyTuple_Size(args); i++) {
1675 if (i > 0) {
1676 if (sep == NULL)
1677 err = PyFile_WriteObject(space, file,
1678 Py_PRINT_RAW);
1679 else
1680 err = PyFile_WriteObject(sep, file,
1681 Py_PRINT_RAW);
1682 if (err)
1683 return NULL;
1684 }
1685 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1686 Py_PRINT_RAW);
1687 if (err)
1688 return NULL;
1689 }
Eric Smith7c478942008-03-18 23:45:49 +00001690
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001691 if (end == NULL)
1692 err = PyFile_WriteObject(newline, file, Py_PRINT_RAW);
1693 else
1694 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1695 if (err)
1696 return NULL;
Eric Smith7c478942008-03-18 23:45:49 +00001697
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001698 Py_RETURN_NONE;
Eric Smith7c478942008-03-18 23:45:49 +00001699}
1700
1701PyDoc_STRVAR(print_doc,
1702"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
1703\n\
1704Prints the values to a stream, or to sys.stdout by default.\n\
1705Optional keyword arguments:\n\
1706file: a file-like object (stream); defaults to the current sys.stdout.\n\
1707sep: string inserted between values, default a space.\n\
1708end: string appended after the last value, default a newline.");
1709
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001710
1711/* Return number of items in range (lo, hi, step), when arguments are
1712 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1713 * & only if the true value is too large to fit in a signed long.
1714 * Arguments MUST return 1 with either PyInt_Check() or
1715 * PyLong_Check(). Return -1 when there is an error.
1716 */
1717static long
1718get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
1719{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001720 /* -------------------------------------------------------------
1721 Algorithm is equal to that of get_len_of_range(), but it operates
1722 on PyObjects (which are assumed to be PyLong or PyInt objects).
1723 ---------------------------------------------------------------*/
1724 long n;
1725 PyObject *diff = NULL;
1726 PyObject *one = NULL;
1727 PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
1728 /* holds sub-expression evaluations */
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001729
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001730 /* if (lo >= hi), return length of 0. */
1731 if (PyObject_Compare(lo, hi) >= 0)
1732 return 0;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001733
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001734 if ((one = PyLong_FromLong(1L)) == NULL)
1735 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001736
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001737 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
1738 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001739
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001740 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
1741 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001742
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001743 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
1744 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001745
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001746 if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
1747 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001748
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001749 n = PyLong_AsLong(tmp3);
1750 if (PyErr_Occurred()) { /* Check for Overflow */
1751 PyErr_Clear();
1752 goto Fail;
1753 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001754
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001755 Py_DECREF(tmp3);
1756 Py_DECREF(tmp2);
1757 Py_DECREF(diff);
1758 Py_DECREF(tmp1);
1759 Py_DECREF(one);
1760 return n;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001761
1762 Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001763 Py_XDECREF(tmp3);
1764 Py_XDECREF(tmp2);
1765 Py_XDECREF(diff);
1766 Py_XDECREF(tmp1);
1767 Py_XDECREF(one);
1768 return -1;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001769}
1770
Mark Dickinsona8d26682010-05-04 16:18:25 +00001771/* Helper function for handle_range_longs. If arg is int or long
1772 object, returns it with incremented reference count. If arg is
1773 float, raises type error. As a last resort, creates a new int by
1774 calling arg type's nb_int method if it is defined. Returns NULL
1775 and sets exception on error.
1776
1777 Returns a new reference to an int object. */
1778static PyObject *
1779get_range_long_argument(PyObject *arg, const char *name)
1780{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001781 PyObject *v;
1782 PyNumberMethods *nb;
Serhiy Storchaka48c8bf22018-07-31 09:09:36 +03001783 if (_PyAnyInt_Check(arg)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001784 Py_INCREF(arg);
1785 return arg;
1786 }
1787 if (PyFloat_Check(arg) ||
1788 (nb = Py_TYPE(arg)->tp_as_number) == NULL ||
1789 nb->nb_int == NULL) {
1790 PyErr_Format(PyExc_TypeError,
1791 "range() integer %s argument expected, got %s.",
1792 name, arg->ob_type->tp_name);
1793 return NULL;
1794 }
1795 v = nb->nb_int(arg);
1796 if (v == NULL)
1797 return NULL;
Serhiy Storchaka48c8bf22018-07-31 09:09:36 +03001798 if (_PyAnyInt_Check(v))
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001799 return v;
1800 Py_DECREF(v);
1801 PyErr_SetString(PyExc_TypeError,
1802 "__int__ should return int object");
1803 return NULL;
Mark Dickinsona8d26682010-05-04 16:18:25 +00001804}
1805
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001806/* An extension of builtin_range() that handles the case when PyLong
1807 * arguments are given. */
1808static PyObject *
Mark Dickinsonef9b4ab2010-05-04 16:19:06 +00001809handle_range_longs(PyObject *self, PyObject *args)
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001810{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001811 PyObject *ilow = NULL;
1812 PyObject *ihigh = NULL;
1813 PyObject *istep = NULL;
Tim Peters874e1f72003-04-13 22:13:08 +00001814
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001815 PyObject *low = NULL;
1816 PyObject *high = NULL;
1817 PyObject *step = NULL;
Mark Dickinsona8d26682010-05-04 16:18:25 +00001818
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001819 PyObject *curnum = NULL;
1820 PyObject *v = NULL;
1821 long bign;
1822 Py_ssize_t i, n;
1823 int cmp_result;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001824
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001825 PyObject *zero = PyLong_FromLong(0);
Tim Peters874e1f72003-04-13 22:13:08 +00001826
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001827 if (zero == NULL)
1828 return NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001829
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001830 if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
1831 Py_DECREF(zero);
1832 return NULL;
1833 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001834
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001835 /* Figure out which way we were called, supply defaults, and be
1836 * sure to incref everything so that the decrefs at the end
1837 * are correct. NB: ilow, ihigh and istep are borrowed references.
1838 */
1839 assert(ilow != NULL);
1840 if (ihigh == NULL) {
1841 /* only 1 arg -- it's the upper limit */
1842 ihigh = ilow;
1843 ilow = NULL;
1844 }
Mark Dickinsona8d26682010-05-04 16:18:25 +00001845
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001846 /* convert ihigh if necessary */
1847 assert(ihigh != NULL);
1848 high = get_range_long_argument(ihigh, "end");
1849 if (high == NULL)
1850 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001851
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001852 /* ihigh correct now; do ilow */
1853 if (ilow == NULL) {
1854 Py_INCREF(zero);
1855 low = zero;
1856 }
1857 else {
1858 low = get_range_long_argument(ilow, "start");
1859 if (low == NULL)
1860 goto Fail;
1861 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001862
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001863 /* ilow and ihigh correct now; do istep */
1864 if (istep == NULL)
1865 step = PyLong_FromLong(1);
1866 else
1867 step = get_range_long_argument(istep, "step");
1868 if (step == NULL)
1869 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001870
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001871 if (PyObject_Cmp(step, zero, &cmp_result) == -1)
1872 goto Fail;
Tim Peters874e1f72003-04-13 22:13:08 +00001873
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001874 if (cmp_result == 0) {
1875 PyErr_SetString(PyExc_ValueError,
1876 "range() step argument must not be zero");
1877 goto Fail;
1878 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001879
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001880 if (cmp_result > 0)
1881 bign = get_len_of_range_longs(low, high, step);
1882 else {
1883 PyObject *neg_step = PyNumber_Negative(step);
1884 if (neg_step == NULL)
1885 goto Fail;
1886 bign = get_len_of_range_longs(high, low, neg_step);
1887 Py_DECREF(neg_step);
1888 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001889
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001890 n = (Py_ssize_t)bign;
1891 if (bign < 0 || (long)n != bign) {
1892 PyErr_SetString(PyExc_OverflowError,
1893 "range() result has too many items");
1894 goto Fail;
1895 }
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001896
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001897 v = PyList_New(n);
1898 if (v == NULL)
1899 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001900
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001901 curnum = low;
1902 Py_INCREF(curnum);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001903
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001904 for (i = 0; i < n; i++) {
1905 PyObject *w = PyNumber_Long(curnum);
1906 PyObject *tmp_num;
1907 if (w == NULL)
1908 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001909
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001910 PyList_SET_ITEM(v, i, w);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001911
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001912 tmp_num = PyNumber_Add(curnum, step);
1913 if (tmp_num == NULL)
1914 goto Fail;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001915
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001916 Py_DECREF(curnum);
1917 curnum = tmp_num;
1918 }
1919 Py_DECREF(low);
1920 Py_DECREF(high);
1921 Py_DECREF(step);
1922 Py_DECREF(zero);
1923 Py_DECREF(curnum);
1924 return v;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001925
1926 Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001927 Py_XDECREF(low);
1928 Py_XDECREF(high);
1929 Py_XDECREF(step);
1930 Py_DECREF(zero);
1931 Py_XDECREF(curnum);
1932 Py_XDECREF(v);
1933 return NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001934}
1935
Guido van Rossum124eff01999-02-23 16:11:01 +00001936/* Return number of items in range/xrange (lo, hi, step). step > 0
1937 * required. Return a value < 0 if & only if the true value is too
1938 * large to fit in a signed long.
1939 */
1940static long
Thomas Wouterse28c2962000-07-23 22:21:32 +00001941get_len_of_range(long lo, long hi, long step)
Guido van Rossum124eff01999-02-23 16:11:01 +00001942{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001943 /* -------------------------------------------------------------
1944 If lo >= hi, the range is empty.
1945 Else if n values are in the range, the last one is
1946 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1947 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1948 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1949 the RHS is non-negative and so truncation is the same as the
1950 floor. Letting M be the largest positive long, the worst case
1951 for the RHS numerator is hi=M, lo=-M-1, and then
1952 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1953 precision to compute the RHS exactly.
1954 ---------------------------------------------------------------*/
1955 long n = 0;
1956 if (lo < hi) {
1957 unsigned long uhi = (unsigned long)hi;
1958 unsigned long ulo = (unsigned long)lo;
1959 unsigned long diff = uhi - ulo - 1;
1960 n = (long)(diff / (unsigned long)step + 1);
1961 }
1962 return n;
Guido van Rossum124eff01999-02-23 16:11:01 +00001963}
1964
Guido van Rossum79f25d91997-04-29 20:08:16 +00001965static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001966builtin_range(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001967{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001968 long ilow = 0, ihigh = 0, istep = 1;
1969 long bign;
1970 Py_ssize_t i, n;
Guido van Rossum124eff01999-02-23 16:11:01 +00001971
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001972 PyObject *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001973
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001974 if (PyTuple_Size(args) <= 1) {
1975 if (!PyArg_ParseTuple(args,
1976 "l;range() requires 1-3 int arguments",
1977 &ihigh)) {
1978 PyErr_Clear();
1979 return handle_range_longs(self, args);
1980 }
1981 }
1982 else {
1983 if (!PyArg_ParseTuple(args,
1984 "ll|l;range() requires 1-3 int arguments",
1985 &ilow, &ihigh, &istep)) {
1986 PyErr_Clear();
1987 return handle_range_longs(self, args);
1988 }
1989 }
1990 if (istep == 0) {
1991 PyErr_SetString(PyExc_ValueError,
1992 "range() step argument must not be zero");
1993 return NULL;
1994 }
1995 if (istep > 0)
1996 bign = get_len_of_range(ilow, ihigh, istep);
1997 else
1998 bign = get_len_of_range(ihigh, ilow, -istep);
1999 n = (Py_ssize_t)bign;
2000 if (bign < 0 || (long)n != bign) {
2001 PyErr_SetString(PyExc_OverflowError,
2002 "range() result has too many items");
2003 return NULL;
2004 }
2005 v = PyList_New(n);
2006 if (v == NULL)
2007 return NULL;
2008 for (i = 0; i < n; i++) {
2009 PyObject *w = PyInt_FromLong(ilow);
2010 if (w == NULL) {
2011 Py_DECREF(v);
2012 return NULL;
2013 }
2014 PyList_SET_ITEM(v, i, w);
2015 ilow += istep;
2016 }
2017 return v;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002018}
2019
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002020PyDoc_STRVAR(range_doc,
Chris Jerdonekad4b0002012-10-07 20:37:54 -07002021"range(stop) -> list of integers\n\
2022range(start, stop[, step]) -> list of integers\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002023\n\
2024Return a list containing an arithmetic progression of integers.\n\
2025range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
2026When step is given, it specifies the increment (or decrement).\n\
2027For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002028These are exactly the valid indices for a list of 4 elements.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002029
2030
Guido van Rossum79f25d91997-04-29 20:08:16 +00002031static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002032builtin_raw_input(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002033{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002034 PyObject *v = NULL;
2035 PyObject *fin = PySys_GetObject("stdin");
2036 PyObject *fout = PySys_GetObject("stdout");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002037
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002038 if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
2039 return NULL;
Martin v. Löwis31d2df52002-08-14 15:46:02 +00002040
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002041 if (fin == NULL) {
2042 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
2043 return NULL;
2044 }
2045 if (fout == NULL) {
2046 PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
2047 return NULL;
2048 }
2049 if (PyFile_SoftSpace(fout, 0)) {
2050 if (PyFile_WriteString(" ", fout) != 0)
2051 return NULL;
2052 }
2053 if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
2054 && isatty(fileno(PyFile_AsFile(fin)))
2055 && isatty(fileno(PyFile_AsFile(fout)))) {
2056 PyObject *po;
2057 char *prompt;
2058 char *s;
2059 PyObject *result;
2060 if (v != NULL) {
2061 po = PyObject_Str(v);
2062 if (po == NULL)
2063 return NULL;
2064 prompt = PyString_AsString(po);
2065 if (prompt == NULL)
2066 return NULL;
2067 }
2068 else {
2069 po = NULL;
2070 prompt = "";
2071 }
2072 s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
2073 prompt);
2074 Py_XDECREF(po);
2075 if (s == NULL) {
2076 if (!PyErr_Occurred())
2077 PyErr_SetNone(PyExc_KeyboardInterrupt);
2078 return NULL;
2079 }
2080 if (*s == '\0') {
2081 PyErr_SetNone(PyExc_EOFError);
2082 result = NULL;
2083 }
2084 else { /* strip trailing '\n' */
2085 size_t len = strlen(s);
2086 if (len > PY_SSIZE_T_MAX) {
2087 PyErr_SetString(PyExc_OverflowError,
2088 "[raw_]input: input too long");
2089 result = NULL;
2090 }
2091 else {
2092 result = PyString_FromStringAndSize(s, len-1);
2093 }
2094 }
2095 PyMem_FREE(s);
2096 return result;
2097 }
2098 if (v != NULL) {
2099 if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
2100 return NULL;
2101 }
2102 return PyFile_GetLine(fin, -1);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002103}
2104
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002105PyDoc_STRVAR(raw_input_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002106"raw_input([prompt]) -> string\n\
2107\n\
2108Read a string from standard input. The trailing newline is stripped.\n\
2109If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
2110On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002111is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002112
2113
Guido van Rossum79f25d91997-04-29 20:08:16 +00002114static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002115builtin_reduce(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002116{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002117 static PyObject *functools_reduce = NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002118
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002119 if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
2120 "use functools.reduce()", 1) < 0)
2121 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +00002122
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002123 if (functools_reduce == NULL) {
2124 PyObject *functools = PyImport_ImportModule("functools");
2125 if (functools == NULL)
2126 return NULL;
2127 functools_reduce = PyObject_GetAttrString(functools, "reduce");
2128 Py_DECREF(functools);
2129 if (functools_reduce == NULL)
2130 return NULL;
2131 }
2132 return PyObject_Call(functools_reduce, args, NULL);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002133}
2134
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002135PyDoc_STRVAR(reduce_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002136"reduce(function, sequence[, initial]) -> value\n\
2137\n\
2138Apply a function of two arguments cumulatively to the items of a sequence,\n\
2139from left to right, so as to reduce the sequence to a single value.\n\
2140For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
2141((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
2142of the sequence in the calculation, and serves as a default when the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002143sequence is empty.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002144
2145
Guido van Rossum79f25d91997-04-29 20:08:16 +00002146static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002147builtin_reload(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002148{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002149 if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
2150 1) < 0)
2151 return NULL;
Neal Norwitzdf25efe2007-05-23 06:58:36 +00002152
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002153 return PyImport_ReloadModule(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002154}
2155
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002156PyDoc_STRVAR(reload_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002157"reload(module) -> module\n\
2158\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002159Reload the module. The module must have been successfully imported before.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002160
2161
Guido van Rossum79f25d91997-04-29 20:08:16 +00002162static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002163builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00002164{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002165 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002166}
2167
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002168PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002169"repr(object) -> string\n\
2170\n\
2171Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002172For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002173
2174
Guido van Rossum79f25d91997-04-29 20:08:16 +00002175static PyObject *
Georg Brandlccadf842006-03-31 18:54:53 +00002176builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002177{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002178 double x;
2179 PyObject *o_ndigits = NULL;
2180 Py_ssize_t ndigits;
2181 static char *kwlist[] = {"number", "ndigits", 0};
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002182
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002183 if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|O:round",
2184 kwlist, &x, &o_ndigits))
2185 return NULL;
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002186
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002187 if (o_ndigits == NULL) {
2188 /* second argument defaults to 0 */
2189 ndigits = 0;
2190 }
2191 else {
2192 /* interpret 2nd argument as a Py_ssize_t; clip on overflow */
2193 ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
2194 if (ndigits == -1 && PyErr_Occurred())
2195 return NULL;
2196 }
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002197
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002198 /* nans, infinities and zeros round to themselves */
2199 if (!Py_IS_FINITE(x) || x == 0.0)
2200 return PyFloat_FromDouble(x);
Mark Dickinsonbce78372009-11-24 10:54:58 +00002201
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002202 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
2203 always rounds to itself. For ndigits < NDIGITS_MIN, x always
2204 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002205#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
2206#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002207 if (ndigits > NDIGITS_MAX)
2208 /* return x */
2209 return PyFloat_FromDouble(x);
2210 else if (ndigits < NDIGITS_MIN)
2211 /* return 0.0, but with sign of x */
2212 return PyFloat_FromDouble(0.0*x);
2213 else
2214 /* finite x, and ndigits is not unreasonably large */
2215 /* _Py_double_round is defined in floatobject.c */
2216 return _Py_double_round(x, (int)ndigits);
Mark Dickinsonbd15a062009-11-18 19:33:35 +00002217#undef NDIGITS_MAX
2218#undef NDIGITS_MIN
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002219}
2220
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002221PyDoc_STRVAR(round_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002222"round(number[, ndigits]) -> floating point number\n\
2223\n\
2224Round a number to a given precision in decimal digits (default 0 digits).\n\
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +00002225This always returns a floating point number. Precision may be negative.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002226
Raymond Hettinger64958a12003-12-17 20:43:33 +00002227static PyObject *
2228builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2229{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002230 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
2231 PyObject *callable;
2232 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
2233 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002234
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002235 /* args 1-4 should match listsort in Objects/listobject.c */
2236 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
2237 kwlist, &seq, &compare, &keyfunc, &reverse))
2238 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002239
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002240 newlist = PySequence_List(seq);
2241 if (newlist == NULL)
2242 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002243
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002244 callable = PyObject_GetAttrString(newlist, "sort");
2245 if (callable == NULL) {
2246 Py_DECREF(newlist);
2247 return NULL;
2248 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002249
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002250 newargs = PyTuple_GetSlice(args, 1, 4);
2251 if (newargs == NULL) {
2252 Py_DECREF(newlist);
2253 Py_DECREF(callable);
2254 return NULL;
2255 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00002256
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002257 v = PyObject_Call(callable, newargs, kwds);
2258 Py_DECREF(newargs);
2259 Py_DECREF(callable);
2260 if (v == NULL) {
2261 Py_DECREF(newlist);
2262 return NULL;
2263 }
2264 Py_DECREF(v);
2265 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002266}
2267
2268PyDoc_STRVAR(sorted_doc,
2269"sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002270
Guido van Rossum79f25d91997-04-29 20:08:16 +00002271static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002272builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002273{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002274 PyObject *v = NULL;
2275 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002276
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002277 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2278 return NULL;
2279 if (v == NULL) {
2280 d = PyEval_GetLocals();
2281 if (d == NULL) {
2282 if (!PyErr_Occurred())
2283 PyErr_SetString(PyExc_SystemError,
2284 "vars(): no locals!?");
2285 }
2286 else
2287 Py_INCREF(d);
2288 }
2289 else {
2290 d = PyObject_GetAttrString(v, "__dict__");
2291 if (d == NULL) {
2292 PyErr_SetString(PyExc_TypeError,
2293 "vars() argument must have __dict__ attribute");
2294 return NULL;
2295 }
2296 }
2297 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002298}
2299
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002300PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002301"vars([object]) -> dictionary\n\
2302\n\
2303Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002304With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002305
Alex Martellia70b1912003-04-22 08:12:33 +00002306
2307static PyObject*
2308builtin_sum(PyObject *self, PyObject *args)
2309{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002310 PyObject *seq;
2311 PyObject *result = NULL;
2312 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002313
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002314 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
2315 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002316
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002317 iter = PyObject_GetIter(seq);
2318 if (iter == NULL)
2319 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002320
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002321 if (result == NULL) {
2322 result = PyInt_FromLong(0);
2323 if (result == NULL) {
2324 Py_DECREF(iter);
2325 return NULL;
2326 }
2327 } else {
2328 /* reject string values for 'start' parameter */
2329 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
2330 PyErr_SetString(PyExc_TypeError,
2331 "sum() can't sum strings [use ''.join(seq) instead]");
2332 Py_DECREF(iter);
2333 return NULL;
2334 }
2335 Py_INCREF(result);
2336 }
Alex Martellia70b1912003-04-22 08:12:33 +00002337
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002338#ifndef SLOW_SUM
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002339 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2340 Assumes all inputs are the same type. If the assumption fails, default
2341 to the more general routine.
2342 */
2343 if (PyInt_CheckExact(result)) {
2344 long i_result = PyInt_AS_LONG(result);
2345 Py_DECREF(result);
2346 result = NULL;
2347 while(result == NULL) {
2348 item = PyIter_Next(iter);
2349 if (item == NULL) {
2350 Py_DECREF(iter);
2351 if (PyErr_Occurred())
2352 return NULL;
2353 return PyInt_FromLong(i_result);
2354 }
2355 if (PyInt_CheckExact(item)) {
2356 long b = PyInt_AS_LONG(item);
2357 long x = i_result + b;
2358 if ((x^i_result) >= 0 || (x^b) >= 0) {
2359 i_result = x;
2360 Py_DECREF(item);
2361 continue;
2362 }
2363 }
2364 /* Either overflowed or is not an int. Restore real objects and process normally */
2365 result = PyInt_FromLong(i_result);
Benjamin Peterson67dafd52018-08-23 22:28:39 -07002366 if (result == NULL) {
2367 Py_DECREF(item);
2368 Py_DECREF(iter);
2369 return NULL;
2370 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002371 temp = PyNumber_Add(result, item);
2372 Py_DECREF(result);
2373 Py_DECREF(item);
2374 result = temp;
2375 if (result == NULL) {
2376 Py_DECREF(iter);
2377 return NULL;
2378 }
2379 }
2380 }
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002381
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002382 if (PyFloat_CheckExact(result)) {
2383 double f_result = PyFloat_AS_DOUBLE(result);
2384 Py_DECREF(result);
2385 result = NULL;
2386 while(result == NULL) {
2387 item = PyIter_Next(iter);
2388 if (item == NULL) {
2389 Py_DECREF(iter);
2390 if (PyErr_Occurred())
2391 return NULL;
2392 return PyFloat_FromDouble(f_result);
2393 }
2394 if (PyFloat_CheckExact(item)) {
2395 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2396 f_result += PyFloat_AS_DOUBLE(item);
2397 PyFPE_END_PROTECT(f_result)
2398 Py_DECREF(item);
2399 continue;
2400 }
2401 if (PyInt_CheckExact(item)) {
2402 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2403 f_result += (double)PyInt_AS_LONG(item);
2404 PyFPE_END_PROTECT(f_result)
2405 Py_DECREF(item);
2406 continue;
2407 }
2408 result = PyFloat_FromDouble(f_result);
Miss Islington (bot)45ee4522018-08-24 01:13:19 -04002409 if (result == NULL) {
2410 Py_DECREF(item);
2411 Py_DECREF(iter);
2412 return NULL;
2413 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002414 temp = PyNumber_Add(result, item);
2415 Py_DECREF(result);
2416 Py_DECREF(item);
2417 result = temp;
2418 if (result == NULL) {
2419 Py_DECREF(iter);
2420 return NULL;
2421 }
2422 }
2423 }
Raymond Hettinger3f8caa32007-10-24 01:28:33 +00002424#endif
2425
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002426 for(;;) {
2427 item = PyIter_Next(iter);
2428 if (item == NULL) {
2429 /* error, or end-of-sequence */
2430 if (PyErr_Occurred()) {
2431 Py_DECREF(result);
2432 result = NULL;
2433 }
2434 break;
2435 }
2436 /* It's tempting to use PyNumber_InPlaceAdd instead of
2437 PyNumber_Add here, to avoid quadratic running time
2438 when doing 'sum(list_of_lists, [])'. However, this
2439 would produce a change in behaviour: a snippet like
Mark Dickinson0e0e2152009-10-26 14:18:44 +00002440
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002441 empty = []
2442 sum([[x] for x in range(10)], empty)
Mark Dickinson0e0e2152009-10-26 14:18:44 +00002443
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002444 would change the value of empty. */
2445 temp = PyNumber_Add(result, item);
2446 Py_DECREF(result);
2447 Py_DECREF(item);
2448 result = temp;
2449 if (result == NULL)
2450 break;
2451 }
2452 Py_DECREF(iter);
2453 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002454}
2455
2456PyDoc_STRVAR(sum_doc,
Mariatta536209e2017-06-06 09:12:03 -07002457"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002458\n\
Mariatta536209e2017-06-06 09:12:03 -07002459Return the sum of an iterable or sequence of numbers (NOT strings)\n\
2460plus the value of 'start' (which defaults to 0). When the sequence is\n\
R David Murrayf7c85842013-07-10 16:23:15 -04002461empty, return start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002462
2463
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002464static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002465builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002466{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002467 PyObject *inst;
2468 PyObject *cls;
2469 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002470
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002471 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2472 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002473
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002474 retval = PyObject_IsInstance(inst, cls);
2475 if (retval < 0)
2476 return NULL;
2477 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002478}
2479
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002480PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002481"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002482\n\
2483Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002484With a type as second argument, return whether that is the object's type.\n\
2485The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002486isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002487
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002488
2489static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002490builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002491{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002492 PyObject *derived;
2493 PyObject *cls;
2494 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002495
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002496 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2497 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002498
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002499 retval = PyObject_IsSubclass(derived, cls);
2500 if (retval < 0)
2501 return NULL;
2502 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002503}
2504
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002505PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002506"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002507\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002508Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2509When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2510is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002511
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002512
Barry Warsawbd599b52000-08-03 15:45:29 +00002513static PyObject*
2514builtin_zip(PyObject *self, PyObject *args)
2515{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002516 PyObject *ret;
2517 const Py_ssize_t itemsize = PySequence_Length(args);
2518 Py_ssize_t i;
2519 PyObject *itlist; /* tuple of iterators */
2520 Py_ssize_t len; /* guess at result length */
Barry Warsawbd599b52000-08-03 15:45:29 +00002521
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002522 if (itemsize == 0)
2523 return PyList_New(0);
Raymond Hettingereaef6152003-08-02 07:42:57 +00002524
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002525 /* args must be a tuple */
2526 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002527
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002528 /* Guess at result length: the shortest of the input lengths.
2529 If some argument refuses to say, we refuse to guess too, lest
2530 an argument like xrange(sys.maxint) lead us astray.*/
2531 len = -1; /* unknown */
2532 for (i = 0; i < itemsize; ++i) {
2533 PyObject *item = PyTuple_GET_ITEM(args, i);
2534 Py_ssize_t thislen = _PyObject_LengthHint(item, -2);
2535 if (thislen < 0) {
2536 if (thislen == -1)
2537 return NULL;
2538 len = -1;
2539 break;
2540 }
2541 else if (len < 0 || thislen < len)
2542 len = thislen;
2543 }
Tim Peters67d687a2002-04-29 21:27:32 +00002544
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002545 /* allocate result list */
2546 if (len < 0)
2547 len = 10; /* arbitrary */
2548 if ((ret = PyList_New(len)) == NULL)
2549 return NULL;
Barry Warsawbd599b52000-08-03 15:45:29 +00002550
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002551 /* obtain iterators */
2552 itlist = PyTuple_New(itemsize);
2553 if (itlist == NULL)
2554 goto Fail_ret;
2555 for (i = 0; i < itemsize; ++i) {
2556 PyObject *item = PyTuple_GET_ITEM(args, i);
2557 PyObject *it = PyObject_GetIter(item);
2558 if (it == NULL) {
2559 if (PyErr_ExceptionMatches(PyExc_TypeError))
2560 PyErr_Format(PyExc_TypeError,
2561 "zip argument #%zd must support iteration",
2562 i+1);
2563 goto Fail_ret_itlist;
2564 }
2565 PyTuple_SET_ITEM(itlist, i, it);
2566 }
Barry Warsawbd599b52000-08-03 15:45:29 +00002567
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002568 /* build result into ret list */
2569 for (i = 0; ; ++i) {
2570 int j;
2571 PyObject *next = PyTuple_New(itemsize);
2572 if (!next)
2573 goto Fail_ret_itlist;
Tim Peters8572b4f2001-05-06 01:05:02 +00002574
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002575 for (j = 0; j < itemsize; j++) {
2576 PyObject *it = PyTuple_GET_ITEM(itlist, j);
2577 PyObject *item = PyIter_Next(it);
2578 if (!item) {
2579 if (PyErr_Occurred()) {
2580 Py_DECREF(ret);
2581 ret = NULL;
2582 }
2583 Py_DECREF(next);
2584 Py_DECREF(itlist);
2585 goto Done;
2586 }
2587 PyTuple_SET_ITEM(next, j, item);
2588 }
Tim Peters8572b4f2001-05-06 01:05:02 +00002589
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002590 if (i < len)
2591 PyList_SET_ITEM(ret, i, next);
2592 else {
2593 int status = PyList_Append(ret, next);
2594 Py_DECREF(next);
2595 ++len;
2596 if (status < 0)
2597 goto Fail_ret_itlist;
2598 }
2599 }
Tim Peters8572b4f2001-05-06 01:05:02 +00002600
Tim Peters67d687a2002-04-29 21:27:32 +00002601Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002602 if (ret != NULL && i < len) {
2603 /* The list is too big. */
2604 if (PyList_SetSlice(ret, i, len, NULL) < 0)
2605 return NULL;
2606 }
2607 return ret;
Tim Peters67d687a2002-04-29 21:27:32 +00002608
Tim Peters8572b4f2001-05-06 01:05:02 +00002609Fail_ret_itlist:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002610 Py_DECREF(itlist);
Tim Peters8572b4f2001-05-06 01:05:02 +00002611Fail_ret:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002612 Py_DECREF(ret);
2613 return NULL;
Barry Warsawbd599b52000-08-03 15:45:29 +00002614}
2615
2616
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002617PyDoc_STRVAR(zip_doc,
Barry Warsawbd599b52000-08-03 15:45:29 +00002618"zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2619\n\
2620Return a list of tuples, where each tuple contains the i-th element\n\
2621from each of the argument sequences. The returned list is truncated\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002622in length to the length of the shortest argument sequence.");
Barry Warsawbd599b52000-08-03 15:45:29 +00002623
2624
Guido van Rossum79f25d91997-04-29 20:08:16 +00002625static PyMethodDef builtin_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002626 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2627 {"abs", builtin_abs, METH_O, abs_doc},
2628 {"all", builtin_all, METH_O, all_doc},
2629 {"any", builtin_any, METH_O, any_doc},
2630 {"apply", builtin_apply, METH_VARARGS, apply_doc},
2631 {"bin", builtin_bin, METH_O, bin_doc},
2632 {"callable", builtin_callable, METH_O, callable_doc},
2633 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2634 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
2635 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
2636 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2637 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2638 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2639 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2640 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2641 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
2642 {"filter", builtin_filter, METH_VARARGS, filter_doc},
2643 {"format", builtin_format, METH_VARARGS, format_doc},
2644 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2645 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2646 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2647 {"hash", builtin_hash, METH_O, hash_doc},
2648 {"hex", builtin_hex, METH_O, hex_doc},
2649 {"id", builtin_id, METH_O, id_doc},
2650 {"input", builtin_input, METH_VARARGS, input_doc},
2651 {"intern", builtin_intern, METH_VARARGS, intern_doc},
2652 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2653 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2654 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2655 {"len", builtin_len, METH_O, len_doc},
2656 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2657 {"map", builtin_map, METH_VARARGS, map_doc},
2658 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2659 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2660 {"next", builtin_next, METH_VARARGS, next_doc},
2661 {"oct", builtin_oct, METH_O, oct_doc},
2662 {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
2663 {"ord", builtin_ord, METH_O, ord_doc},
2664 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2665 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2666 {"range", builtin_range, METH_VARARGS, range_doc},
2667 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
2668 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
2669 {"reload", builtin_reload, METH_O, reload_doc},
2670 {"repr", builtin_repr, METH_O, repr_doc},
2671 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2672 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2673 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2674 {"sum", builtin_sum, METH_VARARGS, sum_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002675#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002676 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002677#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002678 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2679 {"zip", builtin_zip, METH_VARARGS, zip_doc},
2680 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002681};
2682
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002683PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002684"Built-in functions, exceptions, and other objects.\n\
2685\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002686Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002687
Guido van Rossum25ce5661997-08-02 03:10:38 +00002688PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002689_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002690{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002691 PyObject *mod, *dict, *debug;
2692 mod = Py_InitModule4("__builtin__", builtin_methods,
2693 builtin_doc, (PyObject *)NULL,
2694 PYTHON_API_VERSION);
2695 if (mod == NULL)
2696 return NULL;
2697 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002698
Tim Peters7571a0f2003-03-23 17:52:28 +00002699#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002700 /* __builtin__ exposes a number of statically allocated objects
2701 * that, before this code was added in 2.3, never showed up in
2702 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2703 * result, programs leaking references to None and False (etc)
2704 * couldn't be diagnosed by examining sys.getobjects(0).
2705 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002706#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2707#else
2708#define ADD_TO_ALL(OBJECT) (void)0
2709#endif
2710
Tim Peters4b7625e2001-09-13 21:37:17 +00002711#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002712 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2713 return NULL; \
2714 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002715
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002716 SETBUILTIN("None", Py_None);
2717 SETBUILTIN("Ellipsis", Py_Ellipsis);
2718 SETBUILTIN("NotImplemented", Py_NotImplemented);
2719 SETBUILTIN("False", Py_False);
2720 SETBUILTIN("True", Py_True);
2721 SETBUILTIN("basestring", &PyBaseString_Type);
2722 SETBUILTIN("bool", &PyBool_Type);
2723 SETBUILTIN("memoryview", &PyMemoryView_Type);
2724 SETBUILTIN("bytearray", &PyByteArray_Type);
2725 SETBUILTIN("bytes", &PyString_Type);
2726 SETBUILTIN("buffer", &PyBuffer_Type);
2727 SETBUILTIN("classmethod", &PyClassMethod_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002728#ifndef WITHOUT_COMPLEX
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002729 SETBUILTIN("complex", &PyComplex_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002730#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002731 SETBUILTIN("dict", &PyDict_Type);
2732 SETBUILTIN("enumerate", &PyEnum_Type);
2733 SETBUILTIN("file", &PyFile_Type);
2734 SETBUILTIN("float", &PyFloat_Type);
2735 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2736 SETBUILTIN("property", &PyProperty_Type);
2737 SETBUILTIN("int", &PyInt_Type);
2738 SETBUILTIN("list", &PyList_Type);
2739 SETBUILTIN("long", &PyLong_Type);
2740 SETBUILTIN("object", &PyBaseObject_Type);
2741 SETBUILTIN("reversed", &PyReversed_Type);
2742 SETBUILTIN("set", &PySet_Type);
2743 SETBUILTIN("slice", &PySlice_Type);
2744 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2745 SETBUILTIN("str", &PyString_Type);
2746 SETBUILTIN("super", &PySuper_Type);
2747 SETBUILTIN("tuple", &PyTuple_Type);
2748 SETBUILTIN("type", &PyType_Type);
2749 SETBUILTIN("xrange", &PyRange_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002750#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002751 SETBUILTIN("unicode", &PyUnicode_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002752#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002753 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2754 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2755 Py_XDECREF(debug);
2756 return NULL;
2757 }
2758 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002759
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002760 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002761#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002762#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002763}
2764
Guido van Rossume77a7571993-11-03 15:01:26 +00002765/* Helper for filter(): filter a tuple through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002766
Guido van Rossum79f25d91997-04-29 20:08:16 +00002767static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002768filtertuple(PyObject *func, PyObject *tuple)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002769{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002770 PyObject *result;
2771 Py_ssize_t i, j;
2772 Py_ssize_t len = PyTuple_Size(tuple);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002773
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002774 if (len == 0) {
2775 if (PyTuple_CheckExact(tuple))
2776 Py_INCREF(tuple);
2777 else
2778 tuple = PyTuple_New(0);
2779 return tuple;
2780 }
Guido van Rossumb7b45621995-08-04 04:07:45 +00002781
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002782 if ((result = PyTuple_New(len)) == NULL)
2783 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002784
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002785 for (i = j = 0; i < len; ++i) {
2786 PyObject *item, *good;
2787 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002788
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002789 if (tuple->ob_type->tp_as_sequence &&
2790 tuple->ob_type->tp_as_sequence->sq_item) {
2791 item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
2792 if (item == NULL)
2793 goto Fail_1;
2794 } else {
2795 PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
2796 goto Fail_1;
2797 }
2798 if (func == Py_None) {
2799 Py_INCREF(item);
2800 good = item;
2801 }
2802 else {
2803 PyObject *arg = PyTuple_Pack(1, item);
2804 if (arg == NULL) {
2805 Py_DECREF(item);
2806 goto Fail_1;
2807 }
2808 good = PyEval_CallObject(func, arg);
2809 Py_DECREF(arg);
2810 if (good == NULL) {
2811 Py_DECREF(item);
2812 goto Fail_1;
2813 }
2814 }
2815 ok = PyObject_IsTrue(good);
2816 Py_DECREF(good);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002817 if (ok > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002818 if (PyTuple_SetItem(result, j++, item) < 0)
2819 goto Fail_1;
2820 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002821 else {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002822 Py_DECREF(item);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002823 if (ok < 0)
2824 goto Fail_1;
2825 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002826 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002827
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002828 if (_PyTuple_Resize(&result, j) < 0)
2829 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002830
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002831 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002832
Guido van Rossum12d12c51993-10-26 17:58:25 +00002833Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002834 Py_DECREF(result);
2835 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002836}
2837
2838
Guido van Rossume77a7571993-11-03 15:01:26 +00002839/* Helper for filter(): filter a string through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002840
Guido van Rossum79f25d91997-04-29 20:08:16 +00002841static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002842filterstring(PyObject *func, PyObject *strobj)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002843{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002844 PyObject *result;
2845 Py_ssize_t i, j;
2846 Py_ssize_t len = PyString_Size(strobj);
2847 Py_ssize_t outlen = len;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002848
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002849 if (func == Py_None) {
2850 /* If it's a real string we can return the original,
2851 * as no character is ever false and __getitem__
2852 * does return this character. If it's a subclass
2853 * we must go through the __getitem__ loop */
2854 if (PyString_CheckExact(strobj)) {
2855 Py_INCREF(strobj);
2856 return strobj;
2857 }
2858 }
2859 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2860 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002861
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002862 for (i = j = 0; i < len; ++i) {
2863 PyObject *item;
2864 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002865
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002866 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2867 if (item == NULL)
2868 goto Fail_1;
2869 if (func==Py_None) {
2870 ok = 1;
2871 } else {
2872 PyObject *arg, *good;
2873 arg = PyTuple_Pack(1, item);
2874 if (arg == NULL) {
2875 Py_DECREF(item);
2876 goto Fail_1;
2877 }
2878 good = PyEval_CallObject(func, arg);
2879 Py_DECREF(arg);
2880 if (good == NULL) {
2881 Py_DECREF(item);
2882 goto Fail_1;
2883 }
2884 ok = PyObject_IsTrue(good);
2885 Py_DECREF(good);
2886 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002887 if (ok > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002888 Py_ssize_t reslen;
2889 if (!PyString_Check(item)) {
2890 PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
2891 " __getitem__ returned different type");
2892 Py_DECREF(item);
2893 goto Fail_1;
2894 }
2895 reslen = PyString_GET_SIZE(item);
2896 if (reslen == 1) {
2897 PyString_AS_STRING(result)[j++] =
2898 PyString_AS_STRING(item)[0];
2899 } else {
2900 /* do we need more space? */
2901 Py_ssize_t need = j;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002902
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002903 /* calculate space requirements while checking for overflow */
2904 if (need > PY_SSIZE_T_MAX - reslen) {
2905 Py_DECREF(item);
2906 goto Fail_1;
2907 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002908
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002909 need += reslen;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002910
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002911 if (need > PY_SSIZE_T_MAX - len) {
2912 Py_DECREF(item);
2913 goto Fail_1;
2914 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002915
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002916 need += len;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002917
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002918 if (need <= i) {
2919 Py_DECREF(item);
2920 goto Fail_1;
2921 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002922
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002923 need = need - i - 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +00002924
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002925 assert(need >= 0);
2926 assert(outlen >= 0);
Gregory P. Smith9d534572008-06-11 07:41:16 +00002927
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002928 if (need > outlen) {
2929 /* overallocate, to avoid reallocations */
2930 if (outlen > PY_SSIZE_T_MAX / 2) {
2931 Py_DECREF(item);
2932 return NULL;
2933 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00002934
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002935 if (need<2*outlen) {
2936 need = 2*outlen;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002937 }
Martin Panterca56dd42016-09-17 07:54:55 +00002938 if (_PyString_Resize(&result, need)) {
2939 Py_DECREF(item);
2940 return NULL;
2941 }
2942 outlen = need;
2943 }
2944 memcpy(
2945 PyString_AS_STRING(result) + j,
2946 PyString_AS_STRING(item),
2947 reslen
2948 );
2949 j += reslen;
2950 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002951 }
2952 Py_DECREF(item);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02002953 if (ok < 0)
2954 goto Fail_1;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002955 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002956
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002957 if (j < outlen)
2958 _PyString_Resize(&result, j);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002959
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002960 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002961
Guido van Rossum12d12c51993-10-26 17:58:25 +00002962Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002963 Py_DECREF(result);
2964 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002965}
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002966
2967#ifdef Py_USING_UNICODE
2968/* Helper for filter(): filter a Unicode object through a function */
2969
2970static PyObject *
2971filterunicode(PyObject *func, PyObject *strobj)
2972{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002973 PyObject *result;
2974 register Py_ssize_t i, j;
2975 Py_ssize_t len = PyUnicode_GetSize(strobj);
2976 Py_ssize_t outlen = len;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002977
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002978 if (func == Py_None) {
2979 /* If it's a real string we can return the original,
2980 * as no character is ever false and __getitem__
2981 * does return this character. If it's a subclass
2982 * we must go through the __getitem__ loop */
2983 if (PyUnicode_CheckExact(strobj)) {
2984 Py_INCREF(strobj);
2985 return strobj;
2986 }
2987 }
2988 if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
2989 return NULL;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002990
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002991 for (i = j = 0; i < len; ++i) {
2992 PyObject *item, *arg, *good;
2993 int ok;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002994
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002995 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2996 if (item == NULL)
2997 goto Fail_1;
2998 if (func == Py_None) {
2999 ok = 1;
3000 } else {
3001 arg = PyTuple_Pack(1, item);
3002 if (arg == NULL) {
3003 Py_DECREF(item);
3004 goto Fail_1;
3005 }
3006 good = PyEval_CallObject(func, arg);
3007 Py_DECREF(arg);
3008 if (good == NULL) {
3009 Py_DECREF(item);
3010 goto Fail_1;
3011 }
3012 ok = PyObject_IsTrue(good);
3013 Py_DECREF(good);
3014 }
Antoine Pitrouc5bef752012-08-15 23:16:51 +02003015 if (ok > 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003016 Py_ssize_t reslen;
3017 if (!PyUnicode_Check(item)) {
3018 PyErr_SetString(PyExc_TypeError,
3019 "can't filter unicode to unicode:"
3020 " __getitem__ returned different type");
3021 Py_DECREF(item);
3022 goto Fail_1;
3023 }
3024 reslen = PyUnicode_GET_SIZE(item);
3025 if (reslen == 1)
3026 PyUnicode_AS_UNICODE(result)[j++] =
3027 PyUnicode_AS_UNICODE(item)[0];
3028 else {
3029 /* do we need more space? */
3030 Py_ssize_t need = j + reslen + len - i - 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003031
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003032 /* check that didnt overflow */
3033 if ((j > PY_SSIZE_T_MAX - reslen) ||
3034 ((j + reslen) > PY_SSIZE_T_MAX - len) ||
3035 ((j + reslen + len) < i) ||
3036 ((j + reslen + len - i) <= 0)) {
3037 Py_DECREF(item);
3038 return NULL;
3039 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00003040
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003041 assert(need >= 0);
3042 assert(outlen >= 0);
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003043
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003044 if (need > outlen) {
Martin Panterca56dd42016-09-17 07:54:55 +00003045 /* overallocate, to avoid reallocations */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003046 if (need < 2 * outlen) {
Martin Panterca56dd42016-09-17 07:54:55 +00003047 if (outlen > PY_SSIZE_T_MAX / 2) {
3048 Py_DECREF(item);
3049 return NULL;
3050 } else {
3051 need = 2 * outlen;
3052 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003053 }
Martin Panterca56dd42016-09-17 07:54:55 +00003054
3055 if (PyUnicode_Resize(&result, need) < 0) {
3056 Py_DECREF(item);
3057 goto Fail_1;
3058 }
3059 outlen = need;
3060 }
3061 memcpy(PyUnicode_AS_UNICODE(result) + j,
3062 PyUnicode_AS_UNICODE(item),
3063 reslen*sizeof(Py_UNICODE));
3064 j += reslen;
3065 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003066 }
3067 Py_DECREF(item);
Antoine Pitrouc5bef752012-08-15 23:16:51 +02003068 if (ok < 0)
3069 goto Fail_1;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003070 }
3071
3072 if (j < outlen)
3073 PyUnicode_Resize(&result, j);
3074
3075 return result;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003076
3077Fail_1:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003078 Py_DECREF(result);
3079 return NULL;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00003080}
3081#endif