blob: c33a37ea13be8fa0353867d7c62b56cf29ff583d [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"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +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>
11
Mark Hammond26cffde42001-05-14 12:17:34 +000012/* The default encoding used by the platform file system APIs
13 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000014
15 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
16 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000017*/
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000018#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Mark Hammond26cffde42001-05-14 12:17:34 +000019const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000020int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000021#elif defined(__APPLE__)
22const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000023int Py_HasFileSystemDefaultEncoding = 1;
Mark Hammond26cffde42001-05-14 12:17:34 +000024#else
25const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000027#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000028
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int
30_Py_SetFileSystemEncoding(PyObject *s)
31{
32 PyObject *defenc;
33 if (!PyUnicode_Check(s)) {
34 PyErr_BadInternalCall();
35 return -1;
36 }
37 defenc = _PyUnicode_AsDefaultEncodedString(s, NULL);
38 if (!defenc)
39 return -1;
40 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding)
41 /* A file system encoding was set at run-time */
42 free((char*)Py_FileSystemDefaultEncoding);
43 Py_FileSystemDefaultEncoding = strdup(PyBytes_AsString(defenc));
44 Py_HasFileSystemDefaultEncoding = 0;
45 return 0;
46}
47
Guido van Rossum79f25d91997-04-29 20:08:16 +000048static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000049builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
50{
Guido van Rossumcd16bf62007-06-13 18:07:49 +000051 PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell;
52 PyObject *cls = NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000053 Py_ssize_t nargs, nbases;
54
55 assert(args != NULL);
56 if (!PyTuple_Check(args)) {
57 PyErr_SetString(PyExc_TypeError,
58 "__build_class__: args is not a tuple");
59 return NULL;
60 }
61 nargs = PyTuple_GET_SIZE(args);
62 if (nargs < 2) {
63 PyErr_SetString(PyExc_TypeError,
64 "__build_class__: not enough arguments");
65 return NULL;
66 }
67 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
68 name = PyTuple_GET_ITEM(args, 1);
Neal Norwitz6ea45d32007-08-26 04:19:43 +000069 if (!PyUnicode_Check(name)) {
Guido van Rossum52cc1d82007-03-18 15:41:51 +000070 PyErr_SetString(PyExc_TypeError,
71 "__build_class__: name is not a string");
72 return NULL;
73 }
74 bases = PyTuple_GetSlice(args, 2, nargs);
75 if (bases == NULL)
76 return NULL;
77 nbases = nargs - 2;
78
79 if (kwds == NULL) {
80 meta = NULL;
81 mkw = NULL;
82 }
83 else {
84 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
85 if (mkw == NULL) {
86 Py_DECREF(bases);
87 return NULL;
88 }
89 meta = PyDict_GetItemString(mkw, "metaclass");
90 if (meta != NULL) {
91 Py_INCREF(meta);
92 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
93 Py_DECREF(meta);
94 Py_DECREF(mkw);
95 Py_DECREF(bases);
96 return NULL;
97 }
98 }
99 }
100 if (meta == NULL) {
101 if (PyTuple_GET_SIZE(bases) == 0)
102 meta = (PyObject *) (&PyType_Type);
103 else {
104 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
105 meta = (PyObject *) (base0->ob_type);
106 }
107 Py_INCREF(meta);
108 }
109 prep = PyObject_GetAttrString(meta, "__prepare__");
110 if (prep == NULL) {
111 PyErr_Clear();
112 ns = PyDict_New();
113 }
114 else {
Raymond Hettinger5d1ff002009-01-06 09:37:13 +0000115 PyObject *pargs = PyTuple_Pack(2, name, bases);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000116 if (pargs == NULL) {
117 Py_DECREF(prep);
118 Py_DECREF(meta);
119 Py_XDECREF(mkw);
120 Py_DECREF(bases);
121 return NULL;
122 }
123 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
124 Py_DECREF(pargs);
125 Py_DECREF(prep);
126 if (ns == NULL) {
127 Py_DECREF(meta);
128 Py_XDECREF(mkw);
129 Py_DECREF(bases);
130 return NULL;
131 }
132 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000133 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
134 if (cell != NULL) {
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000135 PyObject *margs;
Raymond Hettinger5d1ff002009-01-06 09:37:13 +0000136 margs = PyTuple_Pack(3, name, bases, ns);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000137 if (margs != NULL) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000138 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000139 Py_DECREF(margs);
140 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000141 if (cls != NULL && PyCell_Check(cell)) {
142 Py_INCREF(cls);
143 PyCell_SET(cell, cls);
144 }
145 Py_DECREF(cell);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000146 }
147 Py_DECREF(ns);
148 Py_DECREF(meta);
149 Py_XDECREF(mkw);
150 Py_DECREF(bases);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000151 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000152}
153
154PyDoc_STRVAR(build_class_doc,
155"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
156\n\
157Internal helper function used by the class statement.");
158
159static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000160builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000161{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000162 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
163 "level", 0};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000164 char *name;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000165 PyObject *globals = NULL;
166 PyObject *locals = NULL;
167 PyObject *fromlist = NULL;
Thomas Woutersf7f438b2006-02-28 16:09:29 +0000168 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000169
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000170 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
171 kwlist, &name, &globals, &locals, &fromlist, &level))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000172 return NULL;
Thomas Woutersf7f438b2006-02-28 16:09:29 +0000173 return PyImport_ImportModuleLevel(name, globals, locals,
174 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000175}
176
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000177PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000178"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000179\n\
180Import a module. The globals are only used to determine the context;\n\
181they are not modified. The locals are currently unused. The fromlist\n\
182should be a list of names to emulate ``from name import ...'', or an\n\
183empty list to emulate ``import name''.\n\
184When importing a module from a package, note that __import__('A.B', ...)\n\
185returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000186fromlist is not empty. Level is used to determine whether to perform \n\
187absolute or relative imports. -1 is the original strategy of attempting\n\
188both absolute and relative imports, 0 is absolute, a positive number\n\
189is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000190
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000191
Guido van Rossum79f25d91997-04-29 20:08:16 +0000192static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000193builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000194{
Guido van Rossum09df08a1998-05-22 00:51:39 +0000195 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000196}
197
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000198PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000199"abs(number) -> number\n\
200\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000201Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000202
Raymond Hettinger96229b12005-03-11 06:49:40 +0000203static PyObject *
204builtin_all(PyObject *self, PyObject *v)
205{
206 PyObject *it, *item;
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000207 PyObject *(*iternext)(PyObject *);
208 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000209
210 it = PyObject_GetIter(v);
211 if (it == NULL)
212 return NULL;
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000213 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000214
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000215 for (;;) {
216 item = iternext(it);
217 if (item == NULL)
218 break;
219 cmp = PyObject_IsTrue(item);
Raymond Hettinger96229b12005-03-11 06:49:40 +0000220 Py_DECREF(item);
221 if (cmp < 0) {
222 Py_DECREF(it);
223 return NULL;
224 }
225 if (cmp == 0) {
226 Py_DECREF(it);
227 Py_RETURN_FALSE;
228 }
229 }
230 Py_DECREF(it);
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000231 if (PyErr_Occurred()) {
232 if (PyErr_ExceptionMatches(PyExc_StopIteration))
233 PyErr_Clear();
234 else
235 return NULL;
236 }
Raymond Hettinger96229b12005-03-11 06:49:40 +0000237 Py_RETURN_TRUE;
238}
239
240PyDoc_STRVAR(all_doc,
241"all(iterable) -> bool\n\
242\n\
243Return True if bool(x) is True for all values x in the iterable.");
244
245static PyObject *
246builtin_any(PyObject *self, PyObject *v)
247{
248 PyObject *it, *item;
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000249 PyObject *(*iternext)(PyObject *);
250 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000251
252 it = PyObject_GetIter(v);
253 if (it == NULL)
254 return NULL;
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000255 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000256
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000257 for (;;) {
258 item = iternext(it);
259 if (item == NULL)
260 break;
261 cmp = PyObject_IsTrue(item);
Raymond Hettinger96229b12005-03-11 06:49:40 +0000262 Py_DECREF(item);
263 if (cmp < 0) {
264 Py_DECREF(it);
265 return NULL;
266 }
267 if (cmp == 1) {
268 Py_DECREF(it);
269 Py_RETURN_TRUE;
270 }
271 }
272 Py_DECREF(it);
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000273 if (PyErr_Occurred()) {
274 if (PyErr_ExceptionMatches(PyExc_StopIteration))
275 PyErr_Clear();
276 else
277 return NULL;
278 }
Raymond Hettinger96229b12005-03-11 06:49:40 +0000279 Py_RETURN_FALSE;
280}
281
282PyDoc_STRVAR(any_doc,
283"any(iterable) -> bool\n\
284\n\
285Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000286
Georg Brandl559e5d72008-06-11 18:37:52 +0000287static PyObject *
288builtin_ascii(PyObject *self, PyObject *v)
289{
290 return PyObject_ASCII(v);
291}
292
293PyDoc_STRVAR(ascii_doc,
294"ascii(object) -> string\n\
295\n\
296As repr(), return a string containing a printable representation of an\n\
297object, but escape the non-ASCII characters in the string returned by\n\
298repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
299to that returned by repr() in Python 2.");
300
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000301
Guido van Rossum79f25d91997-04-29 20:08:16 +0000302static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000303builtin_bin(PyObject *self, PyObject *v)
304{
305 return PyNumber_ToBase(v, 2);
306}
307
308PyDoc_STRVAR(bin_doc,
309"bin(number) -> string\n\
310\n\
311Return the binary representation of an integer or long integer.");
312
313
Raymond Hettinger17301e92008-03-13 00:19:26 +0000314typedef struct {
315 PyObject_HEAD
316 PyObject *func;
317 PyObject *it;
318} filterobject;
319
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000320static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000321filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000322{
Raymond Hettinger17301e92008-03-13 00:19:26 +0000323 PyObject *func, *seq;
324 PyObject *it;
325 filterobject *lz;
326
327 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
Guido van Rossum12d12c51993-10-26 17:58:25 +0000328 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000329
330 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
Georg Brandle35b6572005-07-19 22:20:20 +0000331 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000332
333 /* Get iterator. */
334 it = PyObject_GetIter(seq);
335 if (it == NULL)
336 return NULL;
337
338 /* create filterobject structure */
339 lz = (filterobject *)type->tp_alloc(type, 0);
340 if (lz == NULL) {
341 Py_DECREF(it);
342 return NULL;
343 }
344 Py_INCREF(func);
345 lz->func = func;
346 lz->it = it;
347
348 return (PyObject *)lz;
349}
350
351static void
352filter_dealloc(filterobject *lz)
353{
354 PyObject_GC_UnTrack(lz);
355 Py_XDECREF(lz->func);
356 Py_XDECREF(lz->it);
357 Py_TYPE(lz)->tp_free(lz);
358}
359
360static int
361filter_traverse(filterobject *lz, visitproc visit, void *arg)
362{
363 Py_VISIT(lz->it);
364 Py_VISIT(lz->func);
365 return 0;
366}
367
368static PyObject *
369filter_next(filterobject *lz)
370{
371 PyObject *item;
372 PyObject *it = lz->it;
373 long ok;
374 PyObject *(*iternext)(PyObject *);
375
Raymond Hettinger17301e92008-03-13 00:19:26 +0000376 iternext = *Py_TYPE(it)->tp_iternext;
377 for (;;) {
378 item = iternext(it);
379 if (item == NULL)
380 return NULL;
381
382 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
383 ok = PyObject_IsTrue(item);
384 } else {
385 PyObject *good;
386 good = PyObject_CallFunctionObjArgs(lz->func,
387 item, NULL);
388 if (good == NULL) {
389 Py_DECREF(item);
390 return NULL;
391 }
392 ok = PyObject_IsTrue(good);
393 Py_DECREF(good);
394 }
395 if (ok)
396 return item;
397 Py_DECREF(item);
398 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000399}
400
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000401PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000402"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000403\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000404Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000405is true. If function is None, return the items that are true.");
406
407PyTypeObject PyFilter_Type = {
408 PyVarObject_HEAD_INIT(&PyType_Type, 0)
409 "filter", /* tp_name */
410 sizeof(filterobject), /* tp_basicsize */
411 0, /* tp_itemsize */
412 /* methods */
413 (destructor)filter_dealloc, /* tp_dealloc */
414 0, /* tp_print */
415 0, /* tp_getattr */
416 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +0000417 0, /* tp_reserved */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000418 0, /* tp_repr */
419 0, /* tp_as_number */
420 0, /* tp_as_sequence */
421 0, /* tp_as_mapping */
422 0, /* tp_hash */
423 0, /* tp_call */
424 0, /* tp_str */
425 PyObject_GenericGetAttr, /* tp_getattro */
426 0, /* tp_setattro */
427 0, /* tp_as_buffer */
428 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
429 Py_TPFLAGS_BASETYPE, /* tp_flags */
430 filter_doc, /* tp_doc */
431 (traverseproc)filter_traverse, /* tp_traverse */
432 0, /* tp_clear */
433 0, /* tp_richcompare */
434 0, /* tp_weaklistoffset */
435 PyObject_SelfIter, /* tp_iter */
436 (iternextfunc)filter_next, /* tp_iternext */
437 0, /* tp_methods */
438 0, /* tp_members */
439 0, /* tp_getset */
440 0, /* tp_base */
441 0, /* tp_dict */
442 0, /* tp_descr_get */
443 0, /* tp_descr_set */
444 0, /* tp_dictoffset */
445 0, /* tp_init */
446 PyType_GenericAlloc, /* tp_alloc */
447 filter_new, /* tp_new */
448 PyObject_GC_Del, /* tp_free */
449};
450
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000451
Eric Smith8c663262007-08-25 02:26:07 +0000452static PyObject *
453builtin_format(PyObject *self, PyObject *args)
454{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000455 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000456 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000457
Eric Smith8fd3eba2008-02-17 19:48:00 +0000458 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
459 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000460
Eric Smith8fd3eba2008-02-17 19:48:00 +0000461 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000462}
463
Eric Smith8c663262007-08-25 02:26:07 +0000464PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000465"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000466\n\
Eric Smith81936692007-08-31 01:14:01 +0000467Returns value.__format__(format_spec)\n\
468format_spec defaults to \"\"");
469
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000470static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000471builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000472{
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000473 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000474
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000475 if (!PyArg_ParseTuple(args, "i:chr", &x))
Guido van Rossum09095f32000-03-10 23:00:52 +0000476 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000477
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +0000478 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000479}
480
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000481PyDoc_VAR(chr_doc) = PyDoc_STR(
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000482"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000483\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000484Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000485)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000486#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000487PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000488"\nIf 0x10000 <= i, a surrogate pair is returned."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000489)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000490#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000491;
Guido van Rossum09095f32000-03-10 23:00:52 +0000492
493
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000494static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000495source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000496{
497 char *str;
498 Py_ssize_t size;
499
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000500 if (PyUnicode_Check(cmd)) {
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000501 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000502 cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL);
503 if (cmd == NULL)
504 return NULL;
505 }
Guido van Rossuma4b8d1d2007-08-27 15:02:28 +0000506 else if (!PyObject_CheckReadBuffer(cmd)) {
Georg Brandl2cabc562008-08-28 07:57:16 +0000507 PyErr_Format(PyExc_TypeError,
508 "%s() arg 1 must be a %s object",
509 funcname, what);
Guido van Rossuma4b8d1d2007-08-27 15:02:28 +0000510 return NULL;
511 }
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000512 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
513 return NULL;
514 }
515 if (strlen(str) != size) {
516 PyErr_SetString(PyExc_TypeError,
517 "source code string cannot contain null bytes");
518 return NULL;
519 }
520 return str;
521}
522
Guido van Rossum79f25d91997-04-29 20:08:16 +0000523static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000524builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000525{
526 char *str;
527 char *filename;
528 char *startstr;
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000529 int mode = -1;
Tim Peters6cd6a822001-08-17 22:11:27 +0000530 int dont_inherit = 0;
531 int supplied_flags = 0;
Tim Peters5ba58662001-07-16 02:29:45 +0000532 PyCompilerFlags cf;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000533 PyObject *cmd;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000534 static char *kwlist[] = {"source", "filename", "mode", "flags",
535 "dont_inherit", NULL};
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000536 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000537
Guido van Rossumd8faa362007-04-27 19:54:29 +0000538 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
539 kwlist, &cmd, &filename, &startstr,
540 &supplied_flags, &dont_inherit))
Guido van Rossum5b722181993-03-30 17:46:03 +0000541 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000542
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000543 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000544
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000545 if (supplied_flags &
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000546 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000547 {
Tim Peters6cd6a822001-08-17 22:11:27 +0000548 PyErr_SetString(PyExc_ValueError,
549 "compile(): unrecognised flags");
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000550 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000551 }
552 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
553
Tim Peters6cd6a822001-08-17 22:11:27 +0000554 if (!dont_inherit) {
555 PyEval_MergeCompilerFlags(&cf);
556 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000557
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000558 if (strcmp(startstr, "exec") == 0)
559 mode = 0;
560 else if (strcmp(startstr, "eval") == 0)
561 mode = 1;
562 else if (strcmp(startstr, "single") == 0)
563 mode = 2;
564 else {
565 PyErr_SetString(PyExc_ValueError,
566 "compile() arg 3 must be 'exec', 'eval' or 'single'");
567 return NULL;
568 }
569
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000570 if (PyAST_Check(cmd)) {
571 PyObject *result;
572 if (supplied_flags & PyCF_ONLY_AST) {
573 Py_INCREF(cmd);
574 result = cmd;
575 }
576 else {
577 PyArena *arena;
578 mod_ty mod;
579
580 arena = PyArena_New();
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000581 mod = PyAST_obj2mod(cmd, arena, mode);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000582 if (mod == NULL) {
583 PyArena_Free(arena);
584 return NULL;
585 }
586 result = (PyObject*)PyAST_Compile(mod, filename,
587 &cf, arena);
588 PyArena_Free(arena);
589 }
590 return result;
591 }
592
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000593 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000594 if (str == NULL)
595 return NULL;
596
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000597 return Py_CompileStringFlags(str, filename, start[mode], &cf);
Guido van Rossum5b722181993-03-30 17:46:03 +0000598}
599
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000600PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000601"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000602\n\
603Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000604into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000605The filename will be used for run-time error messages.\n\
606The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000607single (interactive) statement, or 'eval' to compile an expression.\n\
608The flags argument, if present, controls which future statements influence\n\
609the compilation of the code.\n\
610The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
611the effects of any future statements in effect in the code calling\n\
612compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000613in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000614
Guido van Rossum79f25d91997-04-29 20:08:16 +0000615static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000616builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000617{
Tim Peters5d2b77c2001-09-03 05:47:38 +0000618 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000619
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000620 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000621 return NULL;
Tim Peters7eea37e2001-09-04 22:08:56 +0000622 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000623}
624
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000625PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000626"dir([object]) -> list of strings\n"
627"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000628"If called without an argument, return the names in the current scope.\n"
629"Else, return an alphabetized list of names comprising (some of) the attributes\n"
630"of the given object, and of attributes reachable from it.\n"
631"If the object supplies a method named __dir__, it will be used; otherwise\n"
632"the default dir() logic is used and returns:\n"
633" for a module object: the module's attributes.\n"
634" for a class object: its attributes, and recursively the attributes\n"
635" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000636" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000637" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000638
Guido van Rossum79f25d91997-04-29 20:08:16 +0000639static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000640builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000641{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000642 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000643
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000644 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000645 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000646 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000647}
648
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000649PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000650"divmod(x, y) -> (div, mod)\n\
651\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000652Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000653
654
Guido van Rossum79f25d91997-04-29 20:08:16 +0000655static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000656builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000657{
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000658 PyObject *cmd, *result, *tmp = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000659 PyObject *globals = Py_None, *locals = Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000660 char *str;
Tim Peters9fa96be2001-08-17 23:04:59 +0000661 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000662
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000663 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000664 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000665 if (locals != Py_None && !PyMapping_Check(locals)) {
666 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
Raymond Hettinger513ffe82004-07-06 13:44:41 +0000667 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000668 }
669 if (globals != Py_None && !PyDict_Check(globals)) {
Georg Brandl99d7e4e2005-08-31 22:21:15 +0000670 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000671 "globals must be a real dict; try eval(expr, {}, mapping)"
672 : "globals must be a dict");
Raymond Hettinger513ffe82004-07-06 13:44:41 +0000673 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000674 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000675 if (globals == Py_None) {
676 globals = PyEval_GetGlobals();
677 if (locals == Py_None)
678 locals = PyEval_GetLocals();
Guido van Rossum6135a871995-01-09 17:53:26 +0000679 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000680 else if (locals == Py_None)
Guido van Rossum6135a871995-01-09 17:53:26 +0000681 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000682
Georg Brandl77c85e62005-09-15 10:46:13 +0000683 if (globals == NULL || locals == NULL) {
684 PyErr_SetString(PyExc_TypeError,
685 "eval must be given globals and locals "
686 "when called without a frame");
687 return NULL;
688 }
689
Guido van Rossum79f25d91997-04-29 20:08:16 +0000690 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
691 if (PyDict_SetItemString(globals, "__builtins__",
692 PyEval_GetBuiltins()) != 0)
Guido van Rossum6135a871995-01-09 17:53:26 +0000693 return NULL;
694 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000695
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000696 if (PyCode_Check(cmd)) {
Jeremy Hylton733c8932001-12-13 19:51:56 +0000697 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000698 PyErr_SetString(PyExc_TypeError,
699 "code object passed to eval() may not contain free variables");
700 return NULL;
701 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000702 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000703 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000704
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000705 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
706 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000707 if (str == NULL)
Guido van Rossum94390a41992-08-14 15:14:30 +0000708 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000709
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000710 while (*str == ' ' || *str == '\t')
711 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000712
Tim Peters9fa96be2001-08-17 23:04:59 +0000713 (void)PyEval_MergeCompilerFlags(&cf);
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000714 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
715 Py_XDECREF(tmp);
716 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000717}
718
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000719PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000720"eval(source[, globals[, locals]]) -> value\n\
721\n\
722Evaluate the source in the context of globals and locals.\n\
723The source may be a string representing a Python expression\n\
724or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000725The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000726defaulting to the current globals and locals.\n\
727If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000728
Georg Brandl7cae87c2006-09-06 06:51:57 +0000729static PyObject *
730builtin_exec(PyObject *self, PyObject *args)
731{
732 PyObject *v;
733 PyObject *prog, *globals = Py_None, *locals = Py_None;
734 int plain = 0;
735
Raymond Hettinger5d1ff002009-01-06 09:37:13 +0000736 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
Georg Brandl7cae87c2006-09-06 06:51:57 +0000737 return NULL;
738
739 if (globals == Py_None) {
740 globals = PyEval_GetGlobals();
741 if (locals == Py_None) {
742 locals = PyEval_GetLocals();
743 plain = 1;
744 }
745 if (!globals || !locals) {
746 PyErr_SetString(PyExc_SystemError,
747 "globals and locals cannot be NULL");
748 return NULL;
749 }
750 }
751 else if (locals == Py_None)
752 locals = globals;
Georg Brandl2cabc562008-08-28 07:57:16 +0000753
Georg Brandl7cae87c2006-09-06 06:51:57 +0000754 if (!PyDict_Check(globals)) {
755 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
756 globals->ob_type->tp_name);
757 return NULL;
758 }
759 if (!PyMapping_Check(locals)) {
760 PyErr_Format(PyExc_TypeError,
761 "arg 3 must be a mapping or None, not %.100s",
762 locals->ob_type->tp_name);
763 return NULL;
764 }
765 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
766 if (PyDict_SetItemString(globals, "__builtins__",
767 PyEval_GetBuiltins()) != 0)
768 return NULL;
769 }
770
771 if (PyCode_Check(prog)) {
772 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
773 PyErr_SetString(PyExc_TypeError,
774 "code object passed to exec() may not "
775 "contain free variables");
776 return NULL;
777 }
778 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
779 }
Georg Brandl7cae87c2006-09-06 06:51:57 +0000780 else {
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000781 char *str;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000782 PyCompilerFlags cf;
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000783 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
784 str = source_as_string(prog, "exec",
785 "string, bytes or code", &cf);
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000786 if (str == NULL)
Georg Brandl7cae87c2006-09-06 06:51:57 +0000787 return NULL;
788 if (PyEval_MergeCompilerFlags(&cf))
789 v = PyRun_StringFlags(str, Py_file_input, globals,
790 locals, &cf);
791 else
792 v = PyRun_String(str, Py_file_input, globals, locals);
Georg Brandl7cae87c2006-09-06 06:51:57 +0000793 }
794 if (v == NULL)
795 return NULL;
796 Py_DECREF(v);
797 Py_RETURN_NONE;
798}
799
800PyDoc_STRVAR(exec_doc,
801"exec(object[, globals[, locals]])\n\
802\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000803Read and execute code from a object, which can be a string or a code\n\
804object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000805The globals and locals are dictionaries, defaulting to the current\n\
806globals and locals. If only globals is given, locals defaults to it.");
807
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000808
Guido van Rossum79f25d91997-04-29 20:08:16 +0000809static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000810builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000811{
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000812 PyObject *v, *result, *dflt = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000813 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000814
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000815 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
Guido van Rossum33894be1992-01-27 16:53:09 +0000816 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000817
Martin v. Löwis5b222132007-06-10 09:51:05 +0000818 if (!PyUnicode_Check(name)) {
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000819 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +0000820 "getattr(): attribute name must be string");
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000821 return NULL;
822 }
Guido van Rossum950ff291998-06-29 13:38:57 +0000823 result = PyObject_GetAttr(v, name);
Guido van Rossumd8923572001-10-16 21:31:32 +0000824 if (result == NULL && dflt != NULL &&
825 PyErr_ExceptionMatches(PyExc_AttributeError))
826 {
Guido van Rossum950ff291998-06-29 13:38:57 +0000827 PyErr_Clear();
828 Py_INCREF(dflt);
829 result = dflt;
830 }
831 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000832}
833
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000834PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000835"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000836\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000837Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
838When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000839exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000840
841
Guido van Rossum79f25d91997-04-29 20:08:16 +0000842static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000843builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000844{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000845 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000846
Guido van Rossum79f25d91997-04-29 20:08:16 +0000847 d = PyEval_GetGlobals();
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000848 Py_XINCREF(d);
Guido van Rossum872537c1995-07-07 22:43:42 +0000849 return d;
850}
851
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000852PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000853"globals() -> dictionary\n\
854\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000855Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000856
857
Guido van Rossum79f25d91997-04-29 20:08:16 +0000858static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000859builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000860{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000861 PyObject *v;
862 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000863
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000864 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
Guido van Rossum9bfef441993-03-29 10:43:31 +0000865 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000866 if (!PyUnicode_Check(name)) {
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000867 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +0000868 "hasattr(): attribute name must be string");
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000869 return NULL;
870 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000871 v = PyObject_GetAttr(v, name);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000872 if (v == NULL) {
Alexandre Vassalottieca20b62008-05-16 02:54:33 +0000873 if (!PyErr_ExceptionMatches(PyExc_Exception))
874 return NULL;
875 else {
876 PyErr_Clear();
877 Py_INCREF(Py_False);
878 return Py_False;
879 }
Guido van Rossum9bfef441993-03-29 10:43:31 +0000880 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000881 Py_DECREF(v);
Guido van Rossum09df08a1998-05-22 00:51:39 +0000882 Py_INCREF(Py_True);
883 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000884}
885
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000886PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000887"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000888\n\
889Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000890(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000891
892
Guido van Rossum79f25d91997-04-29 20:08:16 +0000893static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000894builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000895{
Guido van Rossum106f2da2000-06-28 21:12:25 +0000896 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000897}
898
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000899PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000900"id(object) -> integer\n\
901\n\
902Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000903simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000904
905
Raymond Hettingera6c60372008-03-13 01:26:19 +0000906/* map object ************************************************************/
907
908typedef struct {
909 PyObject_HEAD
910 PyObject *iters;
911 PyObject *func;
912} mapobject;
913
Guido van Rossum79f25d91997-04-29 20:08:16 +0000914static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000915map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000916{
Raymond Hettingera6c60372008-03-13 01:26:19 +0000917 PyObject *it, *iters, *func;
918 mapobject *lz;
919 Py_ssize_t numargs, i;
920
921 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
Guido van Rossum12d12c51993-10-26 17:58:25 +0000922 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000923
924 numargs = PyTuple_Size(args);
925 if (numargs < 2) {
926 PyErr_SetString(PyExc_TypeError,
927 "map() must have at least two arguments.");
Tim Peters4e9afdc2001-05-03 23:54:49 +0000928 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000929 }
930
931 iters = PyTuple_New(numargs-1);
932 if (iters == NULL)
933 return NULL;
934
935 for (i=1 ; i<numargs ; i++) {
936 /* Get iterator. */
937 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
938 if (it == NULL) {
939 Py_DECREF(iters);
940 return NULL;
941 }
942 PyTuple_SET_ITEM(iters, i-1, it);
943 }
944
945 /* create mapobject structure */
946 lz = (mapobject *)type->tp_alloc(type, 0);
947 if (lz == NULL) {
948 Py_DECREF(iters);
949 return NULL;
950 }
951 lz->iters = iters;
952 func = PyTuple_GET_ITEM(args, 0);
953 Py_INCREF(func);
954 lz->func = func;
955
956 return (PyObject *)lz;
957}
958
959static void
960map_dealloc(mapobject *lz)
961{
962 PyObject_GC_UnTrack(lz);
963 Py_XDECREF(lz->iters);
964 Py_XDECREF(lz->func);
965 Py_TYPE(lz)->tp_free(lz);
966}
967
968static int
969map_traverse(mapobject *lz, visitproc visit, void *arg)
970{
971 Py_VISIT(lz->iters);
972 Py_VISIT(lz->func);
973 return 0;
974}
975
976static PyObject *
977map_next(mapobject *lz)
978{
979 PyObject *val;
980 PyObject *argtuple;
981 PyObject *result;
982 Py_ssize_t numargs, i;
983
984 numargs = PyTuple_Size(lz->iters);
985 argtuple = PyTuple_New(numargs);
986 if (argtuple == NULL)
987 return NULL;
988
989 for (i=0 ; i<numargs ; i++) {
990 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
991 if (val == NULL) {
992 Py_DECREF(argtuple);
993 return NULL;
994 }
995 PyTuple_SET_ITEM(argtuple, i, val);
996 }
997 result = PyObject_Call(lz->func, argtuple, NULL);
998 Py_DECREF(argtuple);
Tim Peters4e9afdc2001-05-03 23:54:49 +0000999 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001000}
1001
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001002PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001003"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001004\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001005Make an iterator that computes the function using arguments from\n\
1006each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001007
Raymond Hettingera6c60372008-03-13 01:26:19 +00001008PyTypeObject PyMap_Type = {
1009 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1010 "map", /* tp_name */
1011 sizeof(mapobject), /* tp_basicsize */
1012 0, /* tp_itemsize */
1013 /* methods */
1014 (destructor)map_dealloc, /* tp_dealloc */
1015 0, /* tp_print */
1016 0, /* tp_getattr */
1017 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001018 0, /* tp_reserved */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001019 0, /* tp_repr */
1020 0, /* tp_as_number */
1021 0, /* tp_as_sequence */
1022 0, /* tp_as_mapping */
1023 0, /* tp_hash */
1024 0, /* tp_call */
1025 0, /* tp_str */
1026 PyObject_GenericGetAttr, /* tp_getattro */
1027 0, /* tp_setattro */
1028 0, /* tp_as_buffer */
1029 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1030 Py_TPFLAGS_BASETYPE, /* tp_flags */
1031 map_doc, /* tp_doc */
1032 (traverseproc)map_traverse, /* tp_traverse */
1033 0, /* tp_clear */
1034 0, /* tp_richcompare */
1035 0, /* tp_weaklistoffset */
1036 PyObject_SelfIter, /* tp_iter */
1037 (iternextfunc)map_next, /* tp_iternext */
1038 0, /* tp_methods */
1039 0, /* tp_members */
1040 0, /* tp_getset */
1041 0, /* tp_base */
1042 0, /* tp_dict */
1043 0, /* tp_descr_get */
1044 0, /* tp_descr_set */
1045 0, /* tp_dictoffset */
1046 0, /* tp_init */
1047 PyType_GenericAlloc, /* tp_alloc */
1048 map_new, /* tp_new */
1049 PyObject_GC_Del, /* tp_free */
1050};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001051
Guido van Rossum79f25d91997-04-29 20:08:16 +00001052static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001053builtin_next(PyObject *self, PyObject *args)
1054{
1055 PyObject *it, *res;
1056 PyObject *def = NULL;
1057
1058 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1059 return NULL;
1060 if (!PyIter_Check(it)) {
1061 PyErr_Format(PyExc_TypeError,
Georg Brandlaaa63922008-04-30 19:47:01 +00001062 "%.200s object is not an iterator",
1063 it->ob_type->tp_name);
Georg Brandla18af4e2007-04-21 15:47:16 +00001064 return NULL;
1065 }
1066
1067 res = (*it->ob_type->tp_iternext)(it);
Georg Brandlaaa63922008-04-30 19:47:01 +00001068 if (res != NULL) {
1069 return res;
1070 } else if (def != NULL) {
1071 if (PyErr_Occurred()) {
1072 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
Georg Brandla18af4e2007-04-21 15:47:16 +00001073 return NULL;
1074 PyErr_Clear();
Georg Brandla18af4e2007-04-21 15:47:16 +00001075 }
Georg Brandlaaa63922008-04-30 19:47:01 +00001076 Py_INCREF(def);
1077 return def;
1078 } else if (PyErr_Occurred()) {
1079 return NULL;
1080 } else {
1081 PyErr_SetNone(PyExc_StopIteration);
1082 return NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001083 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001084}
1085
1086PyDoc_STRVAR(next_doc,
1087"next(iterator[, default])\n\
1088\n\
1089Return the next item from the iterator. If default is given and the iterator\n\
1090is exhausted, it is returned instead of raising StopIteration.");
1091
1092
1093static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001094builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001095{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001096 PyObject *v;
1097 PyObject *name;
1098 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001099
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001100 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
Guido van Rossum33894be1992-01-27 16:53:09 +00001101 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001102 if (PyObject_SetAttr(v, name, value) != 0)
Guido van Rossum33894be1992-01-27 16:53:09 +00001103 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001104 Py_INCREF(Py_None);
1105 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001106}
1107
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001108PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001109"setattr(object, name, value)\n\
1110\n\
1111Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001112``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001113
1114
Guido van Rossum79f25d91997-04-29 20:08:16 +00001115static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001116builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001117{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001118 PyObject *v;
1119 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001120
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001121 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
Guido van Rossum14144fc1994-08-29 12:53:40 +00001122 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001123 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001124 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001125 Py_INCREF(Py_None);
1126 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001127}
1128
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001129PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001130"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001131\n\
1132Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001133``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001134
1135
Guido van Rossum79f25d91997-04-29 20:08:16 +00001136static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001137builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001138{
Guido van Rossum9bfef441993-03-29 10:43:31 +00001139 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001140
Guido van Rossum79f25d91997-04-29 20:08:16 +00001141 x = PyObject_Hash(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001142 if (x == -1)
1143 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00001144 return PyLong_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001145}
1146
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001147PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001148"hash(object) -> integer\n\
1149\n\
1150Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001151the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001152
1153
Guido van Rossum79f25d91997-04-29 20:08:16 +00001154static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001155builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001156{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001157 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001158}
1159
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001160PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001161"hex(number) -> string\n\
1162\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001163Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001164
1165
Guido van Rossum79f25d91997-04-29 20:08:16 +00001166static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001167builtin_iter(PyObject *self, PyObject *args)
1168{
1169 PyObject *v, *w = NULL;
1170
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001171 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001172 return NULL;
1173 if (w == NULL)
1174 return PyObject_GetIter(v);
1175 if (!PyCallable_Check(v)) {
1176 PyErr_SetString(PyExc_TypeError,
1177 "iter(v, w): v must be callable");
1178 return NULL;
1179 }
1180 return PyCallIter_New(v, w);
1181}
1182
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001183PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001184"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001185iter(callable, sentinel) -> iterator\n\
1186\n\
1187Get an iterator from an object. In the first form, the argument must\n\
1188supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001189In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001190
1191
1192static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001193builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001194{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001195 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001196
Jeremy Hylton03657cf2000-07-12 13:05:33 +00001197 res = PyObject_Size(v);
Guido van Rossum8ea9f4d1998-06-29 22:26:50 +00001198 if (res < 0 && PyErr_Occurred())
1199 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00001200 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001201}
1202
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001203PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001204"len(object) -> integer\n\
1205\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001206Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001207
1208
Guido van Rossum79f25d91997-04-29 20:08:16 +00001209static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001210builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001211{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001212 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001213
Guido van Rossum79f25d91997-04-29 20:08:16 +00001214 d = PyEval_GetLocals();
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001215 Py_XINCREF(d);
Guido van Rossum872537c1995-07-07 22:43:42 +00001216 return d;
1217}
1218
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001219PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001220"locals() -> dictionary\n\
1221\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001222Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001223
1224
Guido van Rossum79f25d91997-04-29 20:08:16 +00001225static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001226min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001227{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001228 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Martin v. Löwisfd39ad42004-08-12 14:42:37 +00001229 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001230
Guido van Rossum79f25d91997-04-29 20:08:16 +00001231 if (PyTuple_Size(args) > 1)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001232 v = args;
Martin v. Löwisfd39ad42004-08-12 14:42:37 +00001233 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
Guido van Rossum3f5da241990-12-20 15:06:42 +00001234 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001235
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001236 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1237 keyfunc = PyDict_GetItemString(kwds, "key");
1238 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001239 PyErr_Format(PyExc_TypeError,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001240 "%s() got an unexpected keyword argument", name);
1241 return NULL;
1242 }
Christian Heimesbbffeb62008-01-24 09:42:52 +00001243 Py_INCREF(keyfunc);
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001244 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001245
Tim Petersc3074532001-05-03 07:00:32 +00001246 it = PyObject_GetIter(v);
Christian Heimesbbffeb62008-01-24 09:42:52 +00001247 if (it == NULL) {
1248 Py_XDECREF(keyfunc);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001249 return NULL;
Christian Heimesbbffeb62008-01-24 09:42:52 +00001250 }
Tim Petersc3074532001-05-03 07:00:32 +00001251
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001252 maxitem = NULL; /* the result */
1253 maxval = NULL; /* the value associated with the result */
Brett Cannon9e635cf2004-12-07 00:25:35 +00001254 while (( item = PyIter_Next(it) )) {
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001255 /* get the value from the key function */
1256 if (keyfunc != NULL) {
1257 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1258 if (val == NULL)
1259 goto Fail_it_item;
1260 }
1261 /* no key function; the value is the item */
1262 else {
1263 val = item;
1264 Py_INCREF(val);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001265 }
Tim Petersc3074532001-05-03 07:00:32 +00001266
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001267 /* maximum value and item are unset; set them */
1268 if (maxval == NULL) {
1269 maxitem = item;
1270 maxval = val;
1271 }
1272 /* maximum value and item are set; update them as necessary */
Guido van Rossum2d951851994-08-29 12:52:16 +00001273 else {
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001274 int cmp = PyObject_RichCompareBool(val, maxval, op);
1275 if (cmp < 0)
1276 goto Fail_it_item_and_val;
1277 else if (cmp > 0) {
1278 Py_DECREF(maxval);
1279 Py_DECREF(maxitem);
1280 maxval = val;
1281 maxitem = item;
Guido van Rossum53451b32001-01-17 15:47:24 +00001282 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001283 else {
1284 Py_DECREF(item);
1285 Py_DECREF(val);
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001286 }
Guido van Rossum2d951851994-08-29 12:52:16 +00001287 }
Guido van Rossum3f5da241990-12-20 15:06:42 +00001288 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001289 if (PyErr_Occurred())
1290 goto Fail_it;
1291 if (maxval == NULL) {
Martin v. Löwisfd39ad42004-08-12 14:42:37 +00001292 PyErr_Format(PyExc_ValueError,
1293 "%s() arg is an empty sequence", name);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001294 assert(maxitem == NULL);
1295 }
1296 else
1297 Py_DECREF(maxval);
Tim Petersc3074532001-05-03 07:00:32 +00001298 Py_DECREF(it);
Christian Heimesbbffeb62008-01-24 09:42:52 +00001299 Py_XDECREF(keyfunc);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001300 return maxitem;
1301
1302Fail_it_item_and_val:
1303 Py_DECREF(val);
1304Fail_it_item:
1305 Py_DECREF(item);
1306Fail_it:
1307 Py_XDECREF(maxval);
1308 Py_XDECREF(maxitem);
1309 Py_DECREF(it);
Christian Heimesbbffeb62008-01-24 09:42:52 +00001310 Py_XDECREF(keyfunc);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001311 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001312}
1313
Guido van Rossum79f25d91997-04-29 20:08:16 +00001314static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001315builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001316{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001317 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001318}
1319
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001320PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001321"min(iterable[, key=func]) -> value\n\
1322min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001323\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001324With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001325With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001326
1327
Guido van Rossum79f25d91997-04-29 20:08:16 +00001328static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001329builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001330{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001331 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001332}
1333
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001334PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001335"max(iterable[, key=func]) -> value\n\
1336max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001337\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001338With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001339With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001340
1341
Guido van Rossum79f25d91997-04-29 20:08:16 +00001342static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001343builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001344{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001345 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001346}
1347
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001348PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001349"oct(number) -> string\n\
1350\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001351Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001352
1353
Guido van Rossum79f25d91997-04-29 20:08:16 +00001354static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001355builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001356{
Guido van Rossum09095f32000-03-10 23:00:52 +00001357 long ord;
Martin v. Löwisd96ee902006-02-16 14:37:16 +00001358 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001359
Christian Heimes72b710a2008-05-26 13:28:38 +00001360 if (PyBytes_Check(obj)) {
1361 size = PyBytes_GET_SIZE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001362 if (size == 1) {
Christian Heimes72b710a2008-05-26 13:28:38 +00001363 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
Christian Heimes217cfd12007-12-02 14:31:20 +00001364 return PyLong_FromLong(ord);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001365 }
Guido van Rossum98f97462007-04-13 03:31:13 +00001366 }
1367 else if (PyUnicode_Check(obj)) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001368 size = PyUnicode_GET_SIZE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001369 if (size == 1) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001370 ord = (long)*PyUnicode_AS_UNICODE(obj);
Christian Heimes217cfd12007-12-02 14:31:20 +00001371 return PyLong_FromLong(ord);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001372 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001373#ifndef Py_UNICODE_WIDE
1374 if (size == 2) {
1375 /* Decode a valid surrogate pair */
1376 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1377 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1378 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1379 0xDC00 <= c1 && c1 <= 0xDFFF) {
1380 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1381 0x00010000);
Christian Heimes217cfd12007-12-02 14:31:20 +00001382 return PyLong_FromLong(ord);
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001383 }
1384 }
1385#endif
Guido van Rossum6f376c42007-05-24 14:31:33 +00001386 }
Christian Heimes9c4756e2008-05-26 13:22:05 +00001387 else if (PyByteArray_Check(obj)) {
Guido van Rossum98f97462007-04-13 03:31:13 +00001388 /* XXX Hopefully this is temporary */
Christian Heimes9c4756e2008-05-26 13:22:05 +00001389 size = PyByteArray_GET_SIZE(obj);
Guido van Rossum98f97462007-04-13 03:31:13 +00001390 if (size == 1) {
Christian Heimes9c4756e2008-05-26 13:22:05 +00001391 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
Christian Heimes217cfd12007-12-02 14:31:20 +00001392 return PyLong_FromLong(ord);
Guido van Rossum98f97462007-04-13 03:31:13 +00001393 }
1394 }
1395 else {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001396 PyErr_Format(PyExc_TypeError,
Andrew M. Kuchlingf07aad12000-12-23 14:11:28 +00001397 "ord() expected string of length 1, but " \
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001398 "%.200s found", obj->ob_type->tp_name);
Guido van Rossum09095f32000-03-10 23:00:52 +00001399 return NULL;
1400 }
1401
Guido van Rossumad991772001-01-12 16:03:05 +00001402 PyErr_Format(PyExc_TypeError,
Andrew M. Kuchlingf07aad12000-12-23 14:11:28 +00001403 "ord() expected a character, "
Martin v. Löwisd96ee902006-02-16 14:37:16 +00001404 "but string of length %zd found",
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001405 size);
1406 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001407}
1408
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001409PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001410"ord(c) -> integer\n\
1411\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001412Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001413)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001414#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001415PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001416"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001417)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001418#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001419;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001420
1421
Guido van Rossum79f25d91997-04-29 20:08:16 +00001422static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001423builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001424{
Guido van Rossum09df08a1998-05-22 00:51:39 +00001425 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001426
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001427 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001428 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +00001429 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001430}
1431
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001432PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001433"pow(x, y[, z]) -> number\n\
1434\n\
1435With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001436equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001437
1438
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001439
Guido van Rossum34343512006-11-30 22:13:52 +00001440static PyObject *
1441builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1442{
1443 static char *kwlist[] = {"sep", "end", "file", 0};
Georg Brandl257d3d92007-02-26 10:35:10 +00001444 static PyObject *dummy_args;
Guido van Rossum34343512006-11-30 22:13:52 +00001445 PyObject *sep = NULL, *end = NULL, *file = NULL;
1446 int i, err;
1447
Georg Brandl257d3d92007-02-26 10:35:10 +00001448 if (dummy_args == NULL) {
1449 if (!(dummy_args = PyTuple_New(0)))
1450 return NULL;
1451 }
Georg Brandl88fc6642007-02-09 21:28:07 +00001452 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
Guido van Rossum34343512006-11-30 22:13:52 +00001453 kwlist, &sep, &end, &file))
Christian Heimesfef9bba2007-11-13 15:24:14 +00001454 return NULL;
1455 if (file == NULL || file == Py_None) {
Guido van Rossum34343512006-11-30 22:13:52 +00001456 file = PySys_GetObject("stdout");
Christian Heimesfef9bba2007-11-13 15:24:14 +00001457 /* sys.stdout may be None when FILE* stdout isn't connected */
1458 if (file == Py_None)
1459 Py_RETURN_NONE;
1460 }
Guido van Rossum34343512006-11-30 22:13:52 +00001461
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001462 if (sep && sep != Py_None && !PyUnicode_Check(sep)) {
Georg Brandl16f3e032006-11-30 22:46:03 +00001463 PyErr_Format(PyExc_TypeError,
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001464 "sep must be None or a string, not %.200s",
Georg Brandl16f3e032006-11-30 22:46:03 +00001465 sep->ob_type->tp_name);
1466 return NULL;
1467 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001468 if (end && end != Py_None && !PyUnicode_Check(end)) {
Georg Brandl16f3e032006-11-30 22:46:03 +00001469 PyErr_Format(PyExc_TypeError,
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001470 "end must be None or a string, not %.200s",
Georg Brandl16f3e032006-11-30 22:46:03 +00001471 end->ob_type->tp_name);
1472 return NULL;
1473 }
Guido van Rossum34343512006-11-30 22:13:52 +00001474
1475 for (i = 0; i < PyTuple_Size(args); i++) {
1476 if (i > 0) {
1477 if (sep == NULL || sep == Py_None)
1478 err = PyFile_WriteString(" ", file);
1479 else
1480 err = PyFile_WriteObject(sep, file,
1481 Py_PRINT_RAW);
1482 if (err)
1483 return NULL;
1484 }
1485 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1486 Py_PRINT_RAW);
1487 if (err)
1488 return NULL;
1489 }
1490
1491 if (end == NULL || end == Py_None)
1492 err = PyFile_WriteString("\n", file);
1493 else
1494 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1495 if (err)
1496 return NULL;
1497
1498 Py_RETURN_NONE;
1499}
1500
1501PyDoc_STRVAR(print_doc,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001502"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001503\n\
1504Prints the values to a stream, or to sys.stdout by default.\n\
1505Optional keyword arguments:\n\
1506file: a file-like object (stream); defaults to the current sys.stdout.\n\
1507sep: string inserted between values, default a space.\n\
1508end: string appended after the last value, default a newline.");
1509
1510
Guido van Rossuma88a0332007-02-26 16:59:55 +00001511static PyObject *
1512builtin_input(PyObject *self, PyObject *args)
1513{
Guido van Rossumeba76962007-05-27 09:13:28 +00001514 PyObject *promptarg = NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001515 PyObject *fin = PySys_GetObject("stdin");
1516 PyObject *fout = PySys_GetObject("stdout");
Guido van Rossumeba76962007-05-27 09:13:28 +00001517 PyObject *ferr = PySys_GetObject("stderr");
1518 PyObject *tmp;
1519 long fd;
1520 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001521
Guido van Rossumeba76962007-05-27 09:13:28 +00001522 /* Parse arguments */
1523 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
Guido van Rossuma88a0332007-02-26 16:59:55 +00001524 return NULL;
1525
Guido van Rossumeba76962007-05-27 09:13:28 +00001526 /* Check that stdin/out/err are intact */
Christian Heimes2be03732007-11-15 02:26:46 +00001527 if (fin == NULL || fin == Py_None) {
Guido van Rossumeba76962007-05-27 09:13:28 +00001528 PyErr_SetString(PyExc_RuntimeError,
1529 "input(): lost sys.stdin");
Guido van Rossuma88a0332007-02-26 16:59:55 +00001530 return NULL;
1531 }
Christian Heimes2be03732007-11-15 02:26:46 +00001532 if (fout == NULL || fout == Py_None) {
Guido van Rossumeba76962007-05-27 09:13:28 +00001533 PyErr_SetString(PyExc_RuntimeError,
1534 "input(): lost sys.stdout");
Guido van Rossuma88a0332007-02-26 16:59:55 +00001535 return NULL;
1536 }
Christian Heimes2be03732007-11-15 02:26:46 +00001537 if (ferr == NULL || ferr == Py_None) {
Guido van Rossumeba76962007-05-27 09:13:28 +00001538 PyErr_SetString(PyExc_RuntimeError,
1539 "input(): lost sys.stderr");
1540 return NULL;
1541 }
1542
1543 /* First of all, flush stderr */
1544 tmp = PyObject_CallMethod(ferr, "flush", "");
1545 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001546 PyErr_Clear();
1547 else
1548 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001549
1550 /* We should only use (GNU) readline if Python's sys.stdin and
1551 sys.stdout are the same as C's stdin and stdout, because we
1552 need to pass it those. */
1553 tmp = PyObject_CallMethod(fin, "fileno", "");
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001554 if (tmp == NULL) {
1555 PyErr_Clear();
1556 tty = 0;
1557 }
1558 else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001559 fd = PyLong_AsLong(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001560 Py_DECREF(tmp);
1561 if (fd < 0 && PyErr_Occurred())
1562 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001563 tty = fd == fileno(stdin) && isatty(fd);
1564 }
1565 if (tty) {
1566 tmp = PyObject_CallMethod(fout, "fileno", "");
1567 if (tmp == NULL)
1568 PyErr_Clear();
1569 else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001570 fd = PyLong_AsLong(tmp);
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001571 Py_DECREF(tmp);
1572 if (fd < 0 && PyErr_Occurred())
1573 return NULL;
1574 tty = fd == fileno(stdout) && isatty(fd);
1575 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001576 }
1577
1578 /* If we're interactive, use (GNU) readline */
1579 if (tty) {
Guido van Rossuma88a0332007-02-26 16:59:55 +00001580 PyObject *po;
1581 char *prompt;
1582 char *s;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001583 PyObject *stdin_encoding;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001584 PyObject *result;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001585
1586 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1587 if (!stdin_encoding)
1588 /* stdin is a text stream, so it must have an
1589 encoding. */
1590 return NULL;
Guido van Rossumeba76962007-05-27 09:13:28 +00001591 tmp = PyObject_CallMethod(fout, "flush", "");
1592 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001593 PyErr_Clear();
1594 else
1595 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001596 if (promptarg != NULL) {
Amaury Forgeot d'Arcd0db98f2008-09-21 21:49:01 +00001597 PyObject *stringpo;
1598 PyObject *stdout_encoding;
1599 stdout_encoding = PyObject_GetAttrString(fout,
1600 "encoding");
1601 if (stdout_encoding == NULL) {
1602 Py_DECREF(stdin_encoding);
1603 return NULL;
1604 }
1605 stringpo = PyObject_Str(promptarg);
1606 if (stringpo == NULL) {
1607 Py_DECREF(stdin_encoding);
1608 Py_DECREF(stdout_encoding);
1609 return NULL;
1610 }
1611 po = PyUnicode_AsEncodedString(stringpo,
1612 _PyUnicode_AsString(stdout_encoding), NULL);
1613 Py_DECREF(stdout_encoding);
1614 Py_DECREF(stringpo);
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001615 if (po == NULL) {
1616 Py_DECREF(stdin_encoding);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001617 return NULL;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001618 }
Amaury Forgeot d'Arcd0db98f2008-09-21 21:49:01 +00001619 prompt = PyBytes_AsString(po);
Guido van Rossumeba76962007-05-27 09:13:28 +00001620 if (prompt == NULL) {
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001621 Py_DECREF(stdin_encoding);
Guido van Rossumeba76962007-05-27 09:13:28 +00001622 Py_DECREF(po);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001623 return NULL;
Guido van Rossumeba76962007-05-27 09:13:28 +00001624 }
Guido van Rossuma88a0332007-02-26 16:59:55 +00001625 }
1626 else {
1627 po = NULL;
1628 prompt = "";
1629 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001630 s = PyOS_Readline(stdin, stdout, prompt);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001631 Py_XDECREF(po);
1632 if (s == NULL) {
1633 if (!PyErr_Occurred())
1634 PyErr_SetNone(PyExc_KeyboardInterrupt);
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001635 Py_DECREF(stdin_encoding);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001636 return NULL;
1637 }
1638 if (*s == '\0') {
1639 PyErr_SetNone(PyExc_EOFError);
1640 result = NULL;
1641 }
1642 else { /* strip trailing '\n' */
1643 size_t len = strlen(s);
1644 if (len > PY_SSIZE_T_MAX) {
1645 PyErr_SetString(PyExc_OverflowError,
1646 "input: input too long");
1647 result = NULL;
1648 }
1649 else {
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001650 result = PyUnicode_Decode
1651 (s, len-1,
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001652 _PyUnicode_AsString(stdin_encoding),
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001653 NULL);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001654 }
1655 }
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001656 Py_DECREF(stdin_encoding);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001657 PyMem_FREE(s);
1658 return result;
1659 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001660
1661 /* Fallback if we're not interactive */
1662 if (promptarg != NULL) {
1663 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
Guido van Rossuma88a0332007-02-26 16:59:55 +00001664 return NULL;
1665 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001666 tmp = PyObject_CallMethod(fout, "flush", "");
1667 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001668 PyErr_Clear();
1669 else
1670 Py_DECREF(tmp);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001671 return PyFile_GetLine(fin, -1);
1672}
1673
1674PyDoc_STRVAR(input_doc,
1675"input([prompt]) -> string\n\
1676\n\
1677Read a string from standard input. The trailing newline is stripped.\n\
1678If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1679On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1680is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001681
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001682
Guido van Rossum79f25d91997-04-29 20:08:16 +00001683static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001684builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001685{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001686 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001687}
1688
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001689PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001690"repr(object) -> string\n\
1691\n\
1692Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001693For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001694
1695
Guido van Rossum79f25d91997-04-29 20:08:16 +00001696static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001697builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001698{
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001699 static PyObject *round_str = NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00001700 PyObject *ndigits = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001701 static char *kwlist[] = {"number", "ndigits", 0};
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001702 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001703
Mark Dickinson1124e712009-01-28 21:25:58 +00001704 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1705 kwlist, &number, &ndigits))
1706 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001707
Christian Heimes90aa7642007-12-19 02:45:37 +00001708 if (Py_TYPE(number)->tp_dict == NULL) {
1709 if (PyType_Ready(Py_TYPE(number)) < 0)
Guido van Rossum15d3d042007-08-24 02:02:45 +00001710 return NULL;
1711 }
1712
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001713 if (round_str == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +00001714 round_str = PyUnicode_InternFromString("__round__");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001715 if (round_str == NULL)
Alex Martelliae211f92007-08-22 23:21:33 +00001716 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001717 }
1718
Christian Heimes90aa7642007-12-19 02:45:37 +00001719 round = _PyType_Lookup(Py_TYPE(number), round_str);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001720 if (round == NULL) {
1721 PyErr_Format(PyExc_TypeError,
1722 "type %.100s doesn't define __round__ method",
Christian Heimes90aa7642007-12-19 02:45:37 +00001723 Py_TYPE(number)->tp_name);
Alex Martelliae211f92007-08-22 23:21:33 +00001724 return NULL;
1725 }
1726
Mark Dickinson1124e712009-01-28 21:25:58 +00001727 if (ndigits == NULL)
1728 return PyObject_CallFunction(round, "O", number);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001729 else
Mark Dickinson1124e712009-01-28 21:25:58 +00001730 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001731}
1732
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001733PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001734"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001735\n\
1736Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001737This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001738same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001739
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001740
Raymond Hettinger64958a12003-12-17 20:43:33 +00001741static PyObject *
1742builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1743{
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001744 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001745 PyObject *callable;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001746 static char *kwlist[] = {"iterable", "key", "reverse", 0};
Neal Norwitz6f0d4792005-12-15 06:40:36 +00001747 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001748
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001749 /* args 1-3 should match listsort in Objects/listobject.c */
1750 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1751 kwlist, &seq, &keyfunc, &reverse))
Armin Rigo71d7e702005-09-20 18:13:03 +00001752 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001753
1754 newlist = PySequence_List(seq);
1755 if (newlist == NULL)
1756 return NULL;
1757
1758 callable = PyObject_GetAttrString(newlist, "sort");
1759 if (callable == NULL) {
1760 Py_DECREF(newlist);
1761 return NULL;
1762 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001763
Raymond Hettinger64958a12003-12-17 20:43:33 +00001764 newargs = PyTuple_GetSlice(args, 1, 4);
1765 if (newargs == NULL) {
1766 Py_DECREF(newlist);
1767 Py_DECREF(callable);
1768 return NULL;
1769 }
1770
1771 v = PyObject_Call(callable, newargs, kwds);
1772 Py_DECREF(newargs);
1773 Py_DECREF(callable);
1774 if (v == NULL) {
1775 Py_DECREF(newlist);
1776 return NULL;
1777 }
1778 Py_DECREF(v);
1779 return newlist;
1780}
1781
1782PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001783"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001784
Guido van Rossum79f25d91997-04-29 20:08:16 +00001785static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001786builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001787{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001788 PyObject *v = NULL;
1789 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001790
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001791 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001792 return NULL;
Guido van Rossum2d951851994-08-29 12:52:16 +00001793 if (v == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001794 d = PyEval_GetLocals();
Guido van Rossum53bb7ff1995-07-26 16:26:31 +00001795 if (d == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001796 if (!PyErr_Occurred())
1797 PyErr_SetString(PyExc_SystemError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +00001798 "vars(): no locals!?");
Guido van Rossum53bb7ff1995-07-26 16:26:31 +00001799 }
1800 else
Guido van Rossum79f25d91997-04-29 20:08:16 +00001801 Py_INCREF(d);
Guido van Rossum2d951851994-08-29 12:52:16 +00001802 }
1803 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001804 d = PyObject_GetAttrString(v, "__dict__");
Guido van Rossum2d951851994-08-29 12:52:16 +00001805 if (d == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001806 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2d951851994-08-29 12:52:16 +00001807 "vars() argument must have __dict__ attribute");
1808 return NULL;
1809 }
1810 }
1811 return d;
1812}
1813
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001814PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001815"vars([object]) -> dictionary\n\
1816\n\
1817Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001818With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001819
Alex Martellia70b1912003-04-22 08:12:33 +00001820static PyObject*
1821builtin_sum(PyObject *self, PyObject *args)
1822{
1823 PyObject *seq;
1824 PyObject *result = NULL;
1825 PyObject *temp, *item, *iter;
1826
Raymond Hettinger5cf63942003-10-25 06:41:37 +00001827 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
Alex Martellia70b1912003-04-22 08:12:33 +00001828 return NULL;
1829
1830 iter = PyObject_GetIter(seq);
1831 if (iter == NULL)
1832 return NULL;
1833
1834 if (result == NULL) {
Christian Heimes217cfd12007-12-02 14:31:20 +00001835 result = PyLong_FromLong(0);
Alex Martellia70b1912003-04-22 08:12:33 +00001836 if (result == NULL) {
1837 Py_DECREF(iter);
1838 return NULL;
1839 }
1840 } else {
1841 /* reject string values for 'start' parameter */
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001842 if (PyUnicode_Check(result)) {
Alex Martellia70b1912003-04-22 08:12:33 +00001843 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +00001844 "sum() can't sum strings [use ''.join(seq) instead]");
Alex Martellia70b1912003-04-22 08:12:33 +00001845 Py_DECREF(iter);
1846 return NULL;
1847 }
Christian Heimes9c4756e2008-05-26 13:22:05 +00001848 if (PyByteArray_Check(result)) {
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001849 PyErr_SetString(PyExc_TypeError,
1850 "sum() can't sum bytes [use b''.join(seq) instead]");
1851 Py_DECREF(iter);
1852 return NULL;
1853 }
1854
Alex Martelli41c9f882003-04-22 09:24:48 +00001855 Py_INCREF(result);
Alex Martellia70b1912003-04-22 08:12:33 +00001856 }
1857
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001858#ifndef SLOW_SUM
1859 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1860 Assumes all inputs are the same type. If the assumption fails, default
1861 to the more general routine.
1862 */
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001863 if (PyLong_CheckExact(result)) {
1864 int overflow;
1865 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1866 /* If this already overflowed, don't even enter the loop. */
1867 if (overflow == 0) {
1868 Py_DECREF(result);
1869 result = NULL;
1870 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001871 while(result == NULL) {
1872 item = PyIter_Next(iter);
1873 if (item == NULL) {
1874 Py_DECREF(iter);
1875 if (PyErr_Occurred())
1876 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00001877 return PyLong_FromLong(i_result);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001878 }
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001879 if (PyLong_CheckExact(item)) {
1880 long b = PyLong_AsLongAndOverflow(item, &overflow);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001881 long x = i_result + b;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001882 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001883 i_result = x;
1884 Py_DECREF(item);
1885 continue;
1886 }
1887 }
1888 /* Either overflowed or is not an int. Restore real objects and process normally */
Christian Heimes217cfd12007-12-02 14:31:20 +00001889 result = PyLong_FromLong(i_result);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001890 temp = PyNumber_Add(result, item);
1891 Py_DECREF(result);
1892 Py_DECREF(item);
1893 result = temp;
1894 if (result == NULL) {
1895 Py_DECREF(iter);
1896 return NULL;
1897 }
1898 }
1899 }
1900
1901 if (PyFloat_CheckExact(result)) {
1902 double f_result = PyFloat_AS_DOUBLE(result);
1903 Py_DECREF(result);
1904 result = NULL;
1905 while(result == NULL) {
1906 item = PyIter_Next(iter);
1907 if (item == NULL) {
1908 Py_DECREF(iter);
1909 if (PyErr_Occurred())
1910 return NULL;
1911 return PyFloat_FromDouble(f_result);
1912 }
1913 if (PyFloat_CheckExact(item)) {
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001914 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001915 f_result += PyFloat_AS_DOUBLE(item);
1916 PyFPE_END_PROTECT(f_result)
1917 Py_DECREF(item);
1918 continue;
1919 }
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001920 if (PyLong_CheckExact(item)) {
1921 long value;
1922 int overflow;
1923 value = PyLong_AsLongAndOverflow(item, &overflow);
1924 if (!overflow) {
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001925 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001926 f_result += (double)value;
1927 PyFPE_END_PROTECT(f_result)
1928 Py_DECREF(item);
1929 continue;
1930 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001931 }
1932 result = PyFloat_FromDouble(f_result);
1933 temp = PyNumber_Add(result, item);
1934 Py_DECREF(result);
1935 Py_DECREF(item);
1936 result = temp;
1937 if (result == NULL) {
1938 Py_DECREF(iter);
1939 return NULL;
1940 }
1941 }
1942 }
1943#endif
1944
Alex Martellia70b1912003-04-22 08:12:33 +00001945 for(;;) {
1946 item = PyIter_Next(iter);
1947 if (item == NULL) {
1948 /* error, or end-of-sequence */
1949 if (PyErr_Occurred()) {
1950 Py_DECREF(result);
1951 result = NULL;
1952 }
1953 break;
1954 }
Alex Martellia253e182003-10-25 23:24:14 +00001955 temp = PyNumber_Add(result, item);
Alex Martellia70b1912003-04-22 08:12:33 +00001956 Py_DECREF(result);
1957 Py_DECREF(item);
1958 result = temp;
1959 if (result == NULL)
1960 break;
1961 }
1962 Py_DECREF(iter);
1963 return result;
1964}
1965
1966PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001967"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00001968\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00001969Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
1970of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00001971empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00001972
1973
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001974static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001975builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001976{
1977 PyObject *inst;
1978 PyObject *cls;
Guido van Rossum823649d2001-03-21 18:40:58 +00001979 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001980
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001981 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001982 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00001983
Guido van Rossum823649d2001-03-21 18:40:58 +00001984 retval = PyObject_IsInstance(inst, cls);
1985 if (retval < 0)
Guido van Rossumad991772001-01-12 16:03:05 +00001986 return NULL;
Guido van Rossum77f6a652002-04-03 22:41:51 +00001987 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001988}
1989
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001990PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00001991"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001992\n\
1993Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00001994With a type as second argument, return whether that is the object's type.\n\
1995The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001996isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001997
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001998
1999static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002000builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002001{
2002 PyObject *derived;
2003 PyObject *cls;
2004 int retval;
2005
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00002006 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002007 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002008
Guido van Rossum823649d2001-03-21 18:40:58 +00002009 retval = PyObject_IsSubclass(derived, cls);
2010 if (retval < 0)
2011 return NULL;
Guido van Rossum77f6a652002-04-03 22:41:51 +00002012 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002013}
2014
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002015PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002016"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002017\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002018Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2019When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2020is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002021
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002022
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002023typedef struct {
2024 PyObject_HEAD
2025 Py_ssize_t tuplesize;
2026 PyObject *ittuple; /* tuple of iterators */
2027 PyObject *result;
2028} zipobject;
2029
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002030static PyObject *
2031zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002032{
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002033 zipobject *lz;
2034 Py_ssize_t i;
2035 PyObject *ittuple; /* tuple of iterators */
2036 PyObject *result;
2037 Py_ssize_t tuplesize = PySequence_Length(args);
2038
2039 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2040 return NULL;
2041
Guido van Rossumb65fb332006-08-25 23:26:40 +00002042 /* args must be a tuple */
2043 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002044
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002045 /* obtain iterators */
2046 ittuple = PyTuple_New(tuplesize);
2047 if (ittuple == NULL)
2048 return NULL;
2049 for (i=0; i < tuplesize; ++i) {
2050 PyObject *item = PyTuple_GET_ITEM(args, i);
2051 PyObject *it = PyObject_GetIter(item);
2052 if (it == NULL) {
2053 if (PyErr_ExceptionMatches(PyExc_TypeError))
2054 PyErr_Format(PyExc_TypeError,
2055 "zip argument #%zd must support iteration",
2056 i+1);
2057 Py_DECREF(ittuple);
2058 return NULL;
2059 }
2060 PyTuple_SET_ITEM(ittuple, i, it);
2061 }
2062
2063 /* create a result holder */
2064 result = PyTuple_New(tuplesize);
2065 if (result == NULL) {
2066 Py_DECREF(ittuple);
2067 return NULL;
2068 }
2069 for (i=0 ; i < tuplesize ; i++) {
2070 Py_INCREF(Py_None);
2071 PyTuple_SET_ITEM(result, i, Py_None);
2072 }
2073
2074 /* create zipobject structure */
2075 lz = (zipobject *)type->tp_alloc(type, 0);
2076 if (lz == NULL) {
2077 Py_DECREF(ittuple);
2078 Py_DECREF(result);
2079 return NULL;
2080 }
2081 lz->ittuple = ittuple;
2082 lz->tuplesize = tuplesize;
2083 lz->result = result;
2084
2085 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002086}
2087
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002088static void
2089zip_dealloc(zipobject *lz)
2090{
2091 PyObject_GC_UnTrack(lz);
2092 Py_XDECREF(lz->ittuple);
2093 Py_XDECREF(lz->result);
2094 Py_TYPE(lz)->tp_free(lz);
2095}
2096
2097static int
2098zip_traverse(zipobject *lz, visitproc visit, void *arg)
2099{
2100 Py_VISIT(lz->ittuple);
2101 Py_VISIT(lz->result);
2102 return 0;
2103}
2104
2105static PyObject *
2106zip_next(zipobject *lz)
2107{
2108 Py_ssize_t i;
2109 Py_ssize_t tuplesize = lz->tuplesize;
2110 PyObject *result = lz->result;
2111 PyObject *it;
2112 PyObject *item;
2113 PyObject *olditem;
2114
2115 if (tuplesize == 0)
2116 return NULL;
2117 if (Py_REFCNT(result) == 1) {
2118 Py_INCREF(result);
2119 for (i=0 ; i < tuplesize ; i++) {
2120 it = PyTuple_GET_ITEM(lz->ittuple, i);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002121 item = (*Py_TYPE(it)->tp_iternext)(it);
2122 if (item == NULL) {
2123 Py_DECREF(result);
2124 return NULL;
2125 }
2126 olditem = PyTuple_GET_ITEM(result, i);
2127 PyTuple_SET_ITEM(result, i, item);
2128 Py_DECREF(olditem);
2129 }
2130 } else {
2131 result = PyTuple_New(tuplesize);
2132 if (result == NULL)
2133 return NULL;
2134 for (i=0 ; i < tuplesize ; i++) {
2135 it = PyTuple_GET_ITEM(lz->ittuple, i);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002136 item = (*Py_TYPE(it)->tp_iternext)(it);
2137 if (item == NULL) {
2138 Py_DECREF(result);
2139 return NULL;
2140 }
2141 PyTuple_SET_ITEM(result, i, item);
2142 }
2143 }
2144 return result;
2145}
Barry Warsawbd599b52000-08-03 15:45:29 +00002146
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002147PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002148"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002149\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002150Return a zip object whose .__next__() method returns a tuple where\n\
2151the i-th element comes from the i-th iterable argument. The .__next__()\n\
2152method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002153is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002154
2155PyTypeObject PyZip_Type = {
2156 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2157 "zip", /* tp_name */
2158 sizeof(zipobject), /* tp_basicsize */
2159 0, /* tp_itemsize */
2160 /* methods */
2161 (destructor)zip_dealloc, /* tp_dealloc */
2162 0, /* tp_print */
2163 0, /* tp_getattr */
2164 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002165 0, /* tp_reserved */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002166 0, /* tp_repr */
2167 0, /* tp_as_number */
2168 0, /* tp_as_sequence */
2169 0, /* tp_as_mapping */
2170 0, /* tp_hash */
2171 0, /* tp_call */
2172 0, /* tp_str */
2173 PyObject_GenericGetAttr, /* tp_getattro */
2174 0, /* tp_setattro */
2175 0, /* tp_as_buffer */
2176 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2177 Py_TPFLAGS_BASETYPE, /* tp_flags */
2178 zip_doc, /* tp_doc */
2179 (traverseproc)zip_traverse, /* tp_traverse */
2180 0, /* tp_clear */
2181 0, /* tp_richcompare */
2182 0, /* tp_weaklistoffset */
2183 PyObject_SelfIter, /* tp_iter */
2184 (iternextfunc)zip_next, /* tp_iternext */
2185 0, /* tp_methods */
2186 0, /* tp_members */
2187 0, /* tp_getset */
2188 0, /* tp_base */
2189 0, /* tp_dict */
2190 0, /* tp_descr_get */
2191 0, /* tp_descr_set */
2192 0, /* tp_dictoffset */
2193 0, /* tp_init */
2194 PyType_GenericAlloc, /* tp_alloc */
2195 zip_new, /* tp_new */
2196 PyObject_GC_Del, /* tp_free */
2197};
Barry Warsawbd599b52000-08-03 15:45:29 +00002198
2199
Guido van Rossum79f25d91997-04-29 20:08:16 +00002200static PyMethodDef builtin_methods[] = {
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002201 {"__build_class__", (PyCFunction)builtin___build_class__,
2202 METH_VARARGS | METH_KEYWORDS, build_class_doc},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002203 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002204 {"abs", builtin_abs, METH_O, abs_doc},
Raymond Hettinger96229b12005-03-11 06:49:40 +00002205 {"all", builtin_all, METH_O, all_doc},
2206 {"any", builtin_any, METH_O, any_doc},
Georg Brandl559e5d72008-06-11 18:37:52 +00002207 {"ascii", builtin_ascii, METH_O, ascii_doc},
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002208 {"bin", builtin_bin, METH_O, bin_doc},
Neal Norwitzc2550c72007-08-31 04:17:51 +00002209 {"chr", builtin_chr, METH_VARARGS, chr_doc},
Guido van Rossumd8faa362007-04-27 19:54:29 +00002210 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002211 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2212 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2213 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2214 {"eval", builtin_eval, METH_VARARGS, eval_doc},
Georg Brandl7cae87c2006-09-06 06:51:57 +00002215 {"exec", builtin_exec, METH_VARARGS, exec_doc},
Eric Smith8c663262007-08-25 02:26:07 +00002216 {"format", builtin_format, METH_VARARGS, format_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002217 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2218 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2219 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2220 {"hash", builtin_hash, METH_O, hash_doc},
2221 {"hex", builtin_hex, METH_O, hex_doc},
2222 {"id", builtin_id, METH_O, id_doc},
Guido van Rossuma88a0332007-02-26 16:59:55 +00002223 {"input", builtin_input, METH_VARARGS, input_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002224 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2225 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2226 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2227 {"len", builtin_len, METH_O, len_doc},
2228 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00002229 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2230 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
Georg Brandla18af4e2007-04-21 15:47:16 +00002231 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002232 {"oct", builtin_oct, METH_O, oct_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002233 {"ord", builtin_ord, METH_O, ord_doc},
2234 {"pow", builtin_pow, METH_VARARGS, pow_doc},
Guido van Rossum452bf512007-02-09 05:32:43 +00002235 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002236 {"repr", builtin_repr, METH_O, repr_doc},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002237 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002238 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
Raymond Hettinger64958a12003-12-17 20:43:33 +00002239 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
Alex Martellia70b1912003-04-22 08:12:33 +00002240 {"sum", builtin_sum, METH_VARARGS, sum_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002241 {"vars", builtin_vars, METH_VARARGS, vars_doc},
Guido van Rossumc02e15c1991-12-16 13:03:00 +00002242 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002243};
2244
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002245PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002246"Built-in functions, exceptions, and other objects.\n\
2247\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002248Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002249
Martin v. Löwis1a214512008-06-11 05:26:20 +00002250static struct PyModuleDef builtinsmodule = {
2251 PyModuleDef_HEAD_INIT,
2252 "builtins",
2253 builtin_doc,
Christian Heimes6a27efa2008-10-30 21:48:26 +00002254 -1, /* multiple "initialization" just copies the module dict. */
Martin v. Löwis1a214512008-06-11 05:26:20 +00002255 builtin_methods,
2256 NULL,
2257 NULL,
2258 NULL,
2259 NULL
2260};
2261
2262
Guido van Rossum25ce5661997-08-02 03:10:38 +00002263PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002264_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002265{
Fred Drake5550de32000-06-20 04:54:19 +00002266 PyObject *mod, *dict, *debug;
Martin v. Löwis1a214512008-06-11 05:26:20 +00002267 mod = PyModule_Create(&builtinsmodule);
Guido van Rossum25ce5661997-08-02 03:10:38 +00002268 if (mod == NULL)
2269 return NULL;
2270 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002271
Tim Peters7571a0f2003-03-23 17:52:28 +00002272#ifdef Py_TRACE_REFS
Georg Brandl1a3284e2007-12-02 09:40:06 +00002273 /* "builtins" exposes a number of statically allocated objects
Tim Peters7571a0f2003-03-23 17:52:28 +00002274 * that, before this code was added in 2.3, never showed up in
2275 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2276 * result, programs leaking references to None and False (etc)
2277 * couldn't be diagnosed by examining sys.getobjects(0).
2278 */
2279#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2280#else
2281#define ADD_TO_ALL(OBJECT) (void)0
2282#endif
2283
Tim Peters4b7625e2001-09-13 21:37:17 +00002284#define SETBUILTIN(NAME, OBJECT) \
Tim Peters7571a0f2003-03-23 17:52:28 +00002285 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2286 return NULL; \
2287 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002288
2289 SETBUILTIN("None", Py_None);
2290 SETBUILTIN("Ellipsis", Py_Ellipsis);
2291 SETBUILTIN("NotImplemented", Py_NotImplemented);
Guido van Rossum77f6a652002-04-03 22:41:51 +00002292 SETBUILTIN("False", Py_False);
2293 SETBUILTIN("True", Py_True);
2294 SETBUILTIN("bool", &PyBool_Type);
Guido van Rossumbae07c92007-10-08 02:46:15 +00002295 SETBUILTIN("memoryview", &PyMemoryView_Type);
Christian Heimes9c4756e2008-05-26 13:22:05 +00002296 SETBUILTIN("bytearray", &PyByteArray_Type);
Christian Heimes72b710a2008-05-26 13:28:38 +00002297 SETBUILTIN("bytes", &PyBytes_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00002298 SETBUILTIN("classmethod", &PyClassMethod_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002299#ifndef WITHOUT_COMPLEX
Tim Peters4b7625e2001-09-13 21:37:17 +00002300 SETBUILTIN("complex", &PyComplex_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002301#endif
Tim Petersa427a2b2001-10-29 22:25:45 +00002302 SETBUILTIN("dict", &PyDict_Type);
Tim Peters67d687a2002-04-29 21:27:32 +00002303 SETBUILTIN("enumerate", &PyEnum_Type);
Raymond Hettinger17301e92008-03-13 00:19:26 +00002304 SETBUILTIN("filter", &PyFilter_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00002305 SETBUILTIN("float", &PyFloat_Type);
Raymond Hettingera690a992003-11-16 16:17:49 +00002306 SETBUILTIN("frozenset", &PyFrozenSet_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00002307 SETBUILTIN("property", &PyProperty_Type);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002308 SETBUILTIN("int", &PyLong_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00002309 SETBUILTIN("list", &PyList_Type);
Raymond Hettingera6c60372008-03-13 01:26:19 +00002310 SETBUILTIN("map", &PyMap_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00002311 SETBUILTIN("object", &PyBaseObject_Type);
Guido van Rossum805365e2007-05-07 22:24:25 +00002312 SETBUILTIN("range", &PyRange_Type);
Raymond Hettinger85c20a42003-11-06 14:06:48 +00002313 SETBUILTIN("reversed", &PyReversed_Type);
Raymond Hettingera690a992003-11-16 16:17:49 +00002314 SETBUILTIN("set", &PySet_Type);
Guido van Rossumbea18cc2002-06-14 20:41:17 +00002315 SETBUILTIN("slice", &PySlice_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00002316 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
Guido van Rossum572dbf82007-04-27 23:53:51 +00002317 SETBUILTIN("str", &PyUnicode_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00002318 SETBUILTIN("super", &PySuper_Type);
2319 SETBUILTIN("tuple", &PyTuple_Type);
2320 SETBUILTIN("type", &PyType_Type);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002321 SETBUILTIN("zip", &PyZip_Type);
Guido van Rossum77f6a652002-04-03 22:41:51 +00002322 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
Fred Drake5550de32000-06-20 04:54:19 +00002323 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2324 Py_XDECREF(debug);
Guido van Rossum25ce5661997-08-02 03:10:38 +00002325 return NULL;
Fred Drake5550de32000-06-20 04:54:19 +00002326 }
2327 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002328
Guido van Rossum25ce5661997-08-02 03:10:38 +00002329 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002330#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002331#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002332}