blob: 7c08765b315f869abc1b2a1a36316b6faa6f7656 [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";
Christian Heimesc8967002007-11-30 10:18:26 +000020const int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000021#elif defined(__APPLE__)
22const char *Py_FileSystemDefaultEncoding = "utf-8";
Christian Heimesc8967002007-11-30 10:18:26 +000023const int Py_HasFileSystemDefaultEncoding = 1;
Mark Hammond26cffde42001-05-14 12:17:34 +000024#else
25const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
Christian Heimesc8967002007-11-30 10:18:26 +000026const int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000027#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000028
Guido van Rossum79f25d91997-04-29 20:08:16 +000029static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000030builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
31{
Guido van Rossumcd16bf62007-06-13 18:07:49 +000032 PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell;
33 PyObject *cls = NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000034 Py_ssize_t nargs, nbases;
35
36 assert(args != NULL);
37 if (!PyTuple_Check(args)) {
38 PyErr_SetString(PyExc_TypeError,
39 "__build_class__: args is not a tuple");
40 return NULL;
41 }
42 nargs = PyTuple_GET_SIZE(args);
43 if (nargs < 2) {
44 PyErr_SetString(PyExc_TypeError,
45 "__build_class__: not enough arguments");
46 return NULL;
47 }
48 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
49 name = PyTuple_GET_ITEM(args, 1);
Neal Norwitz6ea45d32007-08-26 04:19:43 +000050 if (!PyUnicode_Check(name)) {
Guido van Rossum52cc1d82007-03-18 15:41:51 +000051 PyErr_SetString(PyExc_TypeError,
52 "__build_class__: name is not a string");
53 return NULL;
54 }
55 bases = PyTuple_GetSlice(args, 2, nargs);
56 if (bases == NULL)
57 return NULL;
58 nbases = nargs - 2;
59
60 if (kwds == NULL) {
61 meta = NULL;
62 mkw = NULL;
63 }
64 else {
65 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
66 if (mkw == NULL) {
67 Py_DECREF(bases);
68 return NULL;
69 }
70 meta = PyDict_GetItemString(mkw, "metaclass");
71 if (meta != NULL) {
72 Py_INCREF(meta);
73 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
74 Py_DECREF(meta);
75 Py_DECREF(mkw);
76 Py_DECREF(bases);
77 return NULL;
78 }
79 }
80 }
81 if (meta == NULL) {
82 if (PyTuple_GET_SIZE(bases) == 0)
83 meta = (PyObject *) (&PyType_Type);
84 else {
85 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
86 meta = (PyObject *) (base0->ob_type);
87 }
88 Py_INCREF(meta);
89 }
90 prep = PyObject_GetAttrString(meta, "__prepare__");
91 if (prep == NULL) {
92 PyErr_Clear();
93 ns = PyDict_New();
94 }
95 else {
96 PyObject *pargs = Py_BuildValue("OO", name, bases);
97 if (pargs == NULL) {
98 Py_DECREF(prep);
99 Py_DECREF(meta);
100 Py_XDECREF(mkw);
101 Py_DECREF(bases);
102 return NULL;
103 }
104 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
105 Py_DECREF(pargs);
106 Py_DECREF(prep);
107 if (ns == NULL) {
108 Py_DECREF(meta);
109 Py_XDECREF(mkw);
110 Py_DECREF(bases);
111 return NULL;
112 }
113 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000114 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
115 if (cell != NULL) {
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000116 PyObject *margs;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000117 margs = Py_BuildValue("OOO", name, bases, ns);
118 if (margs != NULL) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000119 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000120 Py_DECREF(margs);
121 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000122 if (cls != NULL && PyCell_Check(cell)) {
123 Py_INCREF(cls);
124 PyCell_SET(cell, cls);
125 }
126 Py_DECREF(cell);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000127 }
128 Py_DECREF(ns);
129 Py_DECREF(meta);
130 Py_XDECREF(mkw);
131 Py_DECREF(bases);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000132 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000133}
134
135PyDoc_STRVAR(build_class_doc,
136"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
137\n\
138Internal helper function used by the class statement.");
139
140static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000141builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000142{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000143 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
144 "level", 0};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000145 char *name;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000146 PyObject *globals = NULL;
147 PyObject *locals = NULL;
148 PyObject *fromlist = NULL;
Thomas Woutersf7f438b2006-02-28 16:09:29 +0000149 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000150
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000151 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
152 kwlist, &name, &globals, &locals, &fromlist, &level))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000153 return NULL;
Thomas Woutersf7f438b2006-02-28 16:09:29 +0000154 return PyImport_ImportModuleLevel(name, globals, locals,
155 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000156}
157
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000158PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000159"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000160\n\
161Import a module. The globals are only used to determine the context;\n\
162they are not modified. The locals are currently unused. The fromlist\n\
163should be a list of names to emulate ``from name import ...'', or an\n\
164empty list to emulate ``import name''.\n\
165When importing a module from a package, note that __import__('A.B', ...)\n\
166returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000167fromlist is not empty. Level is used to determine whether to perform \n\
168absolute or relative imports. -1 is the original strategy of attempting\n\
169both absolute and relative imports, 0 is absolute, a positive number\n\
170is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000171
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000172
Guido van Rossum79f25d91997-04-29 20:08:16 +0000173static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000174builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000175{
Guido van Rossum09df08a1998-05-22 00:51:39 +0000176 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000177}
178
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000179PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000180"abs(number) -> number\n\
181\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000182Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000183
Raymond Hettinger96229b12005-03-11 06:49:40 +0000184static PyObject *
185builtin_all(PyObject *self, PyObject *v)
186{
187 PyObject *it, *item;
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000188 PyObject *(*iternext)(PyObject *);
189 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000190
191 it = PyObject_GetIter(v);
192 if (it == NULL)
193 return NULL;
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000194 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000195
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000196 for (;;) {
197 item = iternext(it);
198 if (item == NULL)
199 break;
200 cmp = PyObject_IsTrue(item);
Raymond Hettinger96229b12005-03-11 06:49:40 +0000201 Py_DECREF(item);
202 if (cmp < 0) {
203 Py_DECREF(it);
204 return NULL;
205 }
206 if (cmp == 0) {
207 Py_DECREF(it);
208 Py_RETURN_FALSE;
209 }
210 }
211 Py_DECREF(it);
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000212 if (PyErr_Occurred()) {
213 if (PyErr_ExceptionMatches(PyExc_StopIteration))
214 PyErr_Clear();
215 else
216 return NULL;
217 }
Raymond Hettinger96229b12005-03-11 06:49:40 +0000218 Py_RETURN_TRUE;
219}
220
221PyDoc_STRVAR(all_doc,
222"all(iterable) -> bool\n\
223\n\
224Return True if bool(x) is True for all values x in the iterable.");
225
226static PyObject *
227builtin_any(PyObject *self, PyObject *v)
228{
229 PyObject *it, *item;
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000230 PyObject *(*iternext)(PyObject *);
231 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000232
233 it = PyObject_GetIter(v);
234 if (it == NULL)
235 return NULL;
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000236 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000237
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000238 for (;;) {
239 item = iternext(it);
240 if (item == NULL)
241 break;
242 cmp = PyObject_IsTrue(item);
Raymond Hettinger96229b12005-03-11 06:49:40 +0000243 Py_DECREF(item);
244 if (cmp < 0) {
245 Py_DECREF(it);
246 return NULL;
247 }
248 if (cmp == 1) {
249 Py_DECREF(it);
250 Py_RETURN_TRUE;
251 }
252 }
253 Py_DECREF(it);
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000254 if (PyErr_Occurred()) {
255 if (PyErr_ExceptionMatches(PyExc_StopIteration))
256 PyErr_Clear();
257 else
258 return NULL;
259 }
Raymond Hettinger96229b12005-03-11 06:49:40 +0000260 Py_RETURN_FALSE;
261}
262
263PyDoc_STRVAR(any_doc,
264"any(iterable) -> bool\n\
265\n\
266Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000267
Georg Brandl559e5d72008-06-11 18:37:52 +0000268static PyObject *
269builtin_ascii(PyObject *self, PyObject *v)
270{
271 return PyObject_ASCII(v);
272}
273
274PyDoc_STRVAR(ascii_doc,
275"ascii(object) -> string\n\
276\n\
277As repr(), return a string containing a printable representation of an\n\
278object, but escape the non-ASCII characters in the string returned by\n\
279repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
280to that returned by repr() in Python 2.");
281
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000282
Guido van Rossum79f25d91997-04-29 20:08:16 +0000283static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000284builtin_bin(PyObject *self, PyObject *v)
285{
286 return PyNumber_ToBase(v, 2);
287}
288
289PyDoc_STRVAR(bin_doc,
290"bin(number) -> string\n\
291\n\
292Return the binary representation of an integer or long integer.");
293
294
Raymond Hettinger17301e92008-03-13 00:19:26 +0000295typedef struct {
296 PyObject_HEAD
297 PyObject *func;
298 PyObject *it;
299} filterobject;
300
301PyTypeObject PyFilter_Type;
302
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000303static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000304filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000305{
Raymond Hettinger17301e92008-03-13 00:19:26 +0000306 PyObject *func, *seq;
307 PyObject *it;
308 filterobject *lz;
309
310 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
Guido van Rossum12d12c51993-10-26 17:58:25 +0000311 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000312
313 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
Georg Brandle35b6572005-07-19 22:20:20 +0000314 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000315
316 /* Get iterator. */
317 it = PyObject_GetIter(seq);
318 if (it == NULL)
319 return NULL;
320
321 /* create filterobject structure */
322 lz = (filterobject *)type->tp_alloc(type, 0);
323 if (lz == NULL) {
324 Py_DECREF(it);
325 return NULL;
326 }
327 Py_INCREF(func);
328 lz->func = func;
329 lz->it = it;
330
331 return (PyObject *)lz;
332}
333
334static void
335filter_dealloc(filterobject *lz)
336{
337 PyObject_GC_UnTrack(lz);
338 Py_XDECREF(lz->func);
339 Py_XDECREF(lz->it);
340 Py_TYPE(lz)->tp_free(lz);
341}
342
343static int
344filter_traverse(filterobject *lz, visitproc visit, void *arg)
345{
346 Py_VISIT(lz->it);
347 Py_VISIT(lz->func);
348 return 0;
349}
350
351static PyObject *
352filter_next(filterobject *lz)
353{
354 PyObject *item;
355 PyObject *it = lz->it;
356 long ok;
357 PyObject *(*iternext)(PyObject *);
358
359 assert(PyIter_Check(it));
360 iternext = *Py_TYPE(it)->tp_iternext;
361 for (;;) {
362 item = iternext(it);
363 if (item == NULL)
364 return NULL;
365
366 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
367 ok = PyObject_IsTrue(item);
368 } else {
369 PyObject *good;
370 good = PyObject_CallFunctionObjArgs(lz->func,
371 item, NULL);
372 if (good == NULL) {
373 Py_DECREF(item);
374 return NULL;
375 }
376 ok = PyObject_IsTrue(good);
377 Py_DECREF(good);
378 }
379 if (ok)
380 return item;
381 Py_DECREF(item);
382 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000383}
384
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000385PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000386"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000387\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000388Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000389is true. If function is None, return the items that are true.");
390
391PyTypeObject PyFilter_Type = {
392 PyVarObject_HEAD_INIT(&PyType_Type, 0)
393 "filter", /* tp_name */
394 sizeof(filterobject), /* tp_basicsize */
395 0, /* tp_itemsize */
396 /* methods */
397 (destructor)filter_dealloc, /* tp_dealloc */
398 0, /* tp_print */
399 0, /* tp_getattr */
400 0, /* tp_setattr */
401 0, /* tp_compare */
402 0, /* tp_repr */
403 0, /* tp_as_number */
404 0, /* tp_as_sequence */
405 0, /* tp_as_mapping */
406 0, /* tp_hash */
407 0, /* tp_call */
408 0, /* tp_str */
409 PyObject_GenericGetAttr, /* tp_getattro */
410 0, /* tp_setattro */
411 0, /* tp_as_buffer */
412 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
413 Py_TPFLAGS_BASETYPE, /* tp_flags */
414 filter_doc, /* tp_doc */
415 (traverseproc)filter_traverse, /* tp_traverse */
416 0, /* tp_clear */
417 0, /* tp_richcompare */
418 0, /* tp_weaklistoffset */
419 PyObject_SelfIter, /* tp_iter */
420 (iternextfunc)filter_next, /* tp_iternext */
421 0, /* tp_methods */
422 0, /* tp_members */
423 0, /* tp_getset */
424 0, /* tp_base */
425 0, /* tp_dict */
426 0, /* tp_descr_get */
427 0, /* tp_descr_set */
428 0, /* tp_dictoffset */
429 0, /* tp_init */
430 PyType_GenericAlloc, /* tp_alloc */
431 filter_new, /* tp_new */
432 PyObject_GC_Del, /* tp_free */
433};
434
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000435
Eric Smith8c663262007-08-25 02:26:07 +0000436static PyObject *
437builtin_format(PyObject *self, PyObject *args)
438{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000439 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000440 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000441
Eric Smith8fd3eba2008-02-17 19:48:00 +0000442 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
443 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000444
Eric Smith8fd3eba2008-02-17 19:48:00 +0000445 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000446}
447
Eric Smith8c663262007-08-25 02:26:07 +0000448PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000449"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000450\n\
Eric Smith81936692007-08-31 01:14:01 +0000451Returns value.__format__(format_spec)\n\
452format_spec defaults to \"\"");
453
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000454static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000455builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000456{
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000457 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000458
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000459 if (!PyArg_ParseTuple(args, "i:chr", &x))
Guido van Rossum09095f32000-03-10 23:00:52 +0000460 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000461
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +0000462 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000463}
464
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000465PyDoc_VAR(chr_doc) = PyDoc_STR(
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000466"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000467\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000468Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000469)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000470#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000471PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000472"\nIf 0x10000 <= i, a surrogate pair is returned."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000473)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000474#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000475;
Guido van Rossum09095f32000-03-10 23:00:52 +0000476
477
478static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000479builtin_cmp(PyObject *self, PyObject *args)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000480{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000481 PyObject *a, *b;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000482 int c;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000483
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000484 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000485 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000486 if (PyObject_Cmp(a, b, &c) < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000487 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +0000488 return PyLong_FromLong((long)c);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000489}
490
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000491PyDoc_STRVAR(cmp_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000492"cmp(x, y) -> integer\n\
493\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000494Return negative if x<y, zero if x==y, positive if x>y.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000495
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000496
497static char *
Georg Brandl2cabc562008-08-28 07:57:16 +0000498source_as_string(PyObject *cmd, char *funcname, char *what)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000499{
500 char *str;
501 Py_ssize_t size;
502
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000503 if (PyUnicode_Check(cmd)) {
504 cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL);
505 if (cmd == NULL)
506 return NULL;
507 }
Guido van Rossuma4b8d1d2007-08-27 15:02:28 +0000508 else if (!PyObject_CheckReadBuffer(cmd)) {
Georg Brandl2cabc562008-08-28 07:57:16 +0000509 PyErr_Format(PyExc_TypeError,
510 "%s() arg 1 must be a %s object",
511 funcname, what);
Guido van Rossuma4b8d1d2007-08-27 15:02:28 +0000512 return NULL;
513 }
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000514 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
515 return NULL;
516 }
517 if (strlen(str) != size) {
518 PyErr_SetString(PyExc_TypeError,
519 "source code string cannot contain null bytes");
520 return NULL;
521 }
522 return str;
523}
524
Guido van Rossum79f25d91997-04-29 20:08:16 +0000525static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000526builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000527{
528 char *str;
529 char *filename;
530 char *startstr;
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000531 int mode = -1;
Tim Peters6cd6a822001-08-17 22:11:27 +0000532 int dont_inherit = 0;
533 int supplied_flags = 0;
Tim Peters5ba58662001-07-16 02:29:45 +0000534 PyCompilerFlags cf;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000535 PyObject *cmd;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000536 static char *kwlist[] = {"source", "filename", "mode", "flags",
537 "dont_inherit", NULL};
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000538 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000539
Guido van Rossumd8faa362007-04-27 19:54:29 +0000540 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
541 kwlist, &cmd, &filename, &startstr,
542 &supplied_flags, &dont_inherit))
Guido van Rossum5b722181993-03-30 17:46:03 +0000543 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000544
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000545 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000546
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000547 if (supplied_flags &
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000548 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000549 {
Tim Peters6cd6a822001-08-17 22:11:27 +0000550 PyErr_SetString(PyExc_ValueError,
551 "compile(): unrecognised flags");
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000552 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000553 }
554 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
555
Tim Peters6cd6a822001-08-17 22:11:27 +0000556 if (!dont_inherit) {
557 PyEval_MergeCompilerFlags(&cf);
558 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000559
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000560 if (strcmp(startstr, "exec") == 0)
561 mode = 0;
562 else if (strcmp(startstr, "eval") == 0)
563 mode = 1;
564 else if (strcmp(startstr, "single") == 0)
565 mode = 2;
566 else {
567 PyErr_SetString(PyExc_ValueError,
568 "compile() arg 3 must be 'exec', 'eval' or 'single'");
569 return NULL;
570 }
571
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000572 if (PyAST_Check(cmd)) {
573 PyObject *result;
574 if (supplied_flags & PyCF_ONLY_AST) {
575 Py_INCREF(cmd);
576 result = cmd;
577 }
578 else {
579 PyArena *arena;
580 mod_ty mod;
581
582 arena = PyArena_New();
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000583 mod = PyAST_obj2mod(cmd, arena, mode);
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000584 if (mod == NULL) {
585 PyArena_Free(arena);
586 return NULL;
587 }
588 result = (PyObject*)PyAST_Compile(mod, filename,
589 &cf, arena);
590 PyArena_Free(arena);
591 }
592 return result;
593 }
594
Georg Brandl2cabc562008-08-28 07:57:16 +0000595 str = source_as_string(cmd, "compile", "string, bytes, AST or code");
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000596 if (str == NULL)
597 return NULL;
598
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000599 return Py_CompileStringFlags(str, filename, start[mode], &cf);
Guido van Rossum5b722181993-03-30 17:46:03 +0000600}
601
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000602PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000603"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000604\n\
605Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000606into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000607The filename will be used for run-time error messages.\n\
608The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000609single (interactive) statement, or 'eval' to compile an expression.\n\
610The flags argument, if present, controls which future statements influence\n\
611the compilation of the code.\n\
612The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
613the effects of any future statements in effect in the code calling\n\
614compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000615in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000616
Guido van Rossum79f25d91997-04-29 20:08:16 +0000617static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000618builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000619{
Tim Peters5d2b77c2001-09-03 05:47:38 +0000620 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000621
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000622 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000623 return NULL;
Tim Peters7eea37e2001-09-04 22:08:56 +0000624 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000625}
626
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000627PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000628"dir([object]) -> list of strings\n"
629"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000630"If called without an argument, return the names in the current scope.\n"
631"Else, return an alphabetized list of names comprising (some of) the attributes\n"
632"of the given object, and of attributes reachable from it.\n"
633"If the object supplies a method named __dir__, it will be used; otherwise\n"
634"the default dir() logic is used and returns:\n"
635" for a module object: the module's attributes.\n"
636" for a class object: its attributes, and recursively the attributes\n"
637" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000638" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000639" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000640
Guido van Rossum79f25d91997-04-29 20:08:16 +0000641static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000642builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000643{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000644 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000645
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000646 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000647 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000648 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000649}
650
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000651PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000652"divmod(x, y) -> (div, mod)\n\
653\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000654Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000655
656
Guido van Rossum79f25d91997-04-29 20:08:16 +0000657static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000658builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000659{
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000660 PyObject *cmd, *result, *tmp = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000661 PyObject *globals = Py_None, *locals = Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000662 char *str;
Tim Peters9fa96be2001-08-17 23:04:59 +0000663 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000664
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000665 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000666 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000667 if (locals != Py_None && !PyMapping_Check(locals)) {
668 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
Raymond Hettinger513ffe82004-07-06 13:44:41 +0000669 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000670 }
671 if (globals != Py_None && !PyDict_Check(globals)) {
Georg Brandl99d7e4e2005-08-31 22:21:15 +0000672 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000673 "globals must be a real dict; try eval(expr, {}, mapping)"
674 : "globals must be a dict");
Raymond Hettinger513ffe82004-07-06 13:44:41 +0000675 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000676 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000677 if (globals == Py_None) {
678 globals = PyEval_GetGlobals();
679 if (locals == Py_None)
680 locals = PyEval_GetLocals();
Guido van Rossum6135a871995-01-09 17:53:26 +0000681 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000682 else if (locals == Py_None)
Guido van Rossum6135a871995-01-09 17:53:26 +0000683 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000684
Georg Brandl77c85e62005-09-15 10:46:13 +0000685 if (globals == NULL || locals == NULL) {
686 PyErr_SetString(PyExc_TypeError,
687 "eval must be given globals and locals "
688 "when called without a frame");
689 return NULL;
690 }
691
Guido van Rossum79f25d91997-04-29 20:08:16 +0000692 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
693 if (PyDict_SetItemString(globals, "__builtins__",
694 PyEval_GetBuiltins()) != 0)
Guido van Rossum6135a871995-01-09 17:53:26 +0000695 return NULL;
696 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000697
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000698 if (PyCode_Check(cmd)) {
Jeremy Hylton733c8932001-12-13 19:51:56 +0000699 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000700 PyErr_SetString(PyExc_TypeError,
701 "code object passed to eval() may not contain free variables");
702 return NULL;
703 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000704 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000705 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000706
Georg Brandl2cabc562008-08-28 07:57:16 +0000707 str = source_as_string(cmd, "eval", "string, bytes or code");
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000708 if (str == NULL)
Guido van Rossum94390a41992-08-14 15:14:30 +0000709 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000710
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000711 while (*str == ' ' || *str == '\t')
712 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000713
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000714 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Tim Peters9fa96be2001-08-17 23:04:59 +0000715 (void)PyEval_MergeCompilerFlags(&cf);
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000716 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
717 Py_XDECREF(tmp);
718 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000719}
720
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000721PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000722"eval(source[, globals[, locals]]) -> value\n\
723\n\
724Evaluate the source in the context of globals and locals.\n\
725The source may be a string representing a Python expression\n\
726or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000727The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000728defaulting to the current globals and locals.\n\
729If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000730
Georg Brandl7cae87c2006-09-06 06:51:57 +0000731static PyObject *
732builtin_exec(PyObject *self, PyObject *args)
733{
734 PyObject *v;
735 PyObject *prog, *globals = Py_None, *locals = Py_None;
736 int plain = 0;
737
738 if (!PyArg_ParseTuple(args, "O|OO:exec", &prog, &globals, &locals))
739 return NULL;
740
741 if (globals == Py_None) {
742 globals = PyEval_GetGlobals();
743 if (locals == Py_None) {
744 locals = PyEval_GetLocals();
745 plain = 1;
746 }
747 if (!globals || !locals) {
748 PyErr_SetString(PyExc_SystemError,
749 "globals and locals cannot be NULL");
750 return NULL;
751 }
752 }
753 else if (locals == Py_None)
754 locals = globals;
Georg Brandl2cabc562008-08-28 07:57:16 +0000755
Georg Brandl7cae87c2006-09-06 06:51:57 +0000756 if (!PyDict_Check(globals)) {
757 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
758 globals->ob_type->tp_name);
759 return NULL;
760 }
761 if (!PyMapping_Check(locals)) {
762 PyErr_Format(PyExc_TypeError,
763 "arg 3 must be a mapping or None, not %.100s",
764 locals->ob_type->tp_name);
765 return NULL;
766 }
767 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
768 if (PyDict_SetItemString(globals, "__builtins__",
769 PyEval_GetBuiltins()) != 0)
770 return NULL;
771 }
772
773 if (PyCode_Check(prog)) {
774 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
775 PyErr_SetString(PyExc_TypeError,
776 "code object passed to exec() may not "
777 "contain free variables");
778 return NULL;
779 }
780 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
781 }
Georg Brandl7cae87c2006-09-06 06:51:57 +0000782 else {
Georg Brandl2cabc562008-08-28 07:57:16 +0000783 char *str = source_as_string(prog, "exec",
784 "string, bytes or code");
Georg Brandl7cae87c2006-09-06 06:51:57 +0000785 PyCompilerFlags cf;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000786 if (str == NULL)
Georg Brandl7cae87c2006-09-06 06:51:57 +0000787 return NULL;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000788 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000789 if (PyEval_MergeCompilerFlags(&cf))
790 v = PyRun_StringFlags(str, Py_file_input, globals,
791 locals, &cf);
792 else
793 v = PyRun_String(str, Py_file_input, globals, locals);
Georg Brandl7cae87c2006-09-06 06:51:57 +0000794 }
795 if (v == NULL)
796 return NULL;
797 Py_DECREF(v);
798 Py_RETURN_NONE;
799}
800
801PyDoc_STRVAR(exec_doc,
802"exec(object[, globals[, locals]])\n\
803\n\
804Read and execute code from a object, which can be a string, a code\n\
805object or a file object.\n\
806The globals and locals are dictionaries, defaulting to the current\n\
807globals and locals. If only globals is given, locals defaults to it.");
808
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000809
Guido van Rossum79f25d91997-04-29 20:08:16 +0000810static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000811builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000812{
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000813 PyObject *v, *result, *dflt = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000814 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000815
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000816 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
Guido van Rossum33894be1992-01-27 16:53:09 +0000817 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000818
Martin v. Löwis5b222132007-06-10 09:51:05 +0000819 if (!PyUnicode_Check(name)) {
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000820 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +0000821 "getattr(): attribute name must be string");
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000822 return NULL;
823 }
Guido van Rossum950ff291998-06-29 13:38:57 +0000824 result = PyObject_GetAttr(v, name);
Guido van Rossumd8923572001-10-16 21:31:32 +0000825 if (result == NULL && dflt != NULL &&
826 PyErr_ExceptionMatches(PyExc_AttributeError))
827 {
Guido van Rossum950ff291998-06-29 13:38:57 +0000828 PyErr_Clear();
829 Py_INCREF(dflt);
830 result = dflt;
831 }
832 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000833}
834
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000835PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000836"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000837\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000838Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
839When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000840exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000841
842
Guido van Rossum79f25d91997-04-29 20:08:16 +0000843static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000844builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000845{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000846 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000847
Guido van Rossum79f25d91997-04-29 20:08:16 +0000848 d = PyEval_GetGlobals();
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000849 Py_XINCREF(d);
Guido van Rossum872537c1995-07-07 22:43:42 +0000850 return d;
851}
852
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000853PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000854"globals() -> dictionary\n\
855\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000856Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000857
858
Guido van Rossum79f25d91997-04-29 20:08:16 +0000859static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000860builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000861{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000862 PyObject *v;
863 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000864
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000865 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
Guido van Rossum9bfef441993-03-29 10:43:31 +0000866 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000867 if (!PyUnicode_Check(name)) {
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000868 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +0000869 "hasattr(): attribute name must be string");
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000870 return NULL;
871 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000872 v = PyObject_GetAttr(v, name);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000873 if (v == NULL) {
Alexandre Vassalottieca20b62008-05-16 02:54:33 +0000874 if (!PyErr_ExceptionMatches(PyExc_Exception))
875 return NULL;
876 else {
877 PyErr_Clear();
878 Py_INCREF(Py_False);
879 return Py_False;
880 }
Guido van Rossum9bfef441993-03-29 10:43:31 +0000881 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000882 Py_DECREF(v);
Guido van Rossum09df08a1998-05-22 00:51:39 +0000883 Py_INCREF(Py_True);
884 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000885}
886
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000887PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000888"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000889\n\
890Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000891(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000892
893
Guido van Rossum79f25d91997-04-29 20:08:16 +0000894static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000895builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000896{
Guido van Rossum106f2da2000-06-28 21:12:25 +0000897 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000898}
899
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000900PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000901"id(object) -> integer\n\
902\n\
903Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000904simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000905
906
Raymond Hettingera6c60372008-03-13 01:26:19 +0000907/* map object ************************************************************/
908
909typedef struct {
910 PyObject_HEAD
911 PyObject *iters;
912 PyObject *func;
913} mapobject;
914
915PyTypeObject PyMap_Type;
916
Guido van Rossum79f25d91997-04-29 20:08:16 +0000917static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000918map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000919{
Raymond Hettingera6c60372008-03-13 01:26:19 +0000920 PyObject *it, *iters, *func;
921 mapobject *lz;
922 Py_ssize_t numargs, i;
923
924 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
Guido van Rossum12d12c51993-10-26 17:58:25 +0000925 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000926
927 numargs = PyTuple_Size(args);
928 if (numargs < 2) {
929 PyErr_SetString(PyExc_TypeError,
930 "map() must have at least two arguments.");
Tim Peters4e9afdc2001-05-03 23:54:49 +0000931 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000932 }
933
934 iters = PyTuple_New(numargs-1);
935 if (iters == NULL)
936 return NULL;
937
938 for (i=1 ; i<numargs ; i++) {
939 /* Get iterator. */
940 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
941 if (it == NULL) {
942 Py_DECREF(iters);
943 return NULL;
944 }
945 PyTuple_SET_ITEM(iters, i-1, it);
946 }
947
948 /* create mapobject structure */
949 lz = (mapobject *)type->tp_alloc(type, 0);
950 if (lz == NULL) {
951 Py_DECREF(iters);
952 return NULL;
953 }
954 lz->iters = iters;
955 func = PyTuple_GET_ITEM(args, 0);
956 Py_INCREF(func);
957 lz->func = func;
958
959 return (PyObject *)lz;
960}
961
962static void
963map_dealloc(mapobject *lz)
964{
965 PyObject_GC_UnTrack(lz);
966 Py_XDECREF(lz->iters);
967 Py_XDECREF(lz->func);
968 Py_TYPE(lz)->tp_free(lz);
969}
970
971static int
972map_traverse(mapobject *lz, visitproc visit, void *arg)
973{
974 Py_VISIT(lz->iters);
975 Py_VISIT(lz->func);
976 return 0;
977}
978
979static PyObject *
980map_next(mapobject *lz)
981{
982 PyObject *val;
983 PyObject *argtuple;
984 PyObject *result;
985 Py_ssize_t numargs, i;
986
987 numargs = PyTuple_Size(lz->iters);
988 argtuple = PyTuple_New(numargs);
989 if (argtuple == NULL)
990 return NULL;
991
992 for (i=0 ; i<numargs ; i++) {
993 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
994 if (val == NULL) {
995 Py_DECREF(argtuple);
996 return NULL;
997 }
998 PyTuple_SET_ITEM(argtuple, i, val);
999 }
1000 result = PyObject_Call(lz->func, argtuple, NULL);
1001 Py_DECREF(argtuple);
Tim Peters4e9afdc2001-05-03 23:54:49 +00001002 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001003}
1004
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001005PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001006"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001007\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001008Make an iterator that computes the function using arguments from\n\
1009each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001010
Raymond Hettingera6c60372008-03-13 01:26:19 +00001011PyTypeObject PyMap_Type = {
1012 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1013 "map", /* tp_name */
1014 sizeof(mapobject), /* tp_basicsize */
1015 0, /* tp_itemsize */
1016 /* methods */
1017 (destructor)map_dealloc, /* tp_dealloc */
1018 0, /* tp_print */
1019 0, /* tp_getattr */
1020 0, /* tp_setattr */
1021 0, /* tp_compare */
1022 0, /* tp_repr */
1023 0, /* tp_as_number */
1024 0, /* tp_as_sequence */
1025 0, /* tp_as_mapping */
1026 0, /* tp_hash */
1027 0, /* tp_call */
1028 0, /* tp_str */
1029 PyObject_GenericGetAttr, /* tp_getattro */
1030 0, /* tp_setattro */
1031 0, /* tp_as_buffer */
1032 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1033 Py_TPFLAGS_BASETYPE, /* tp_flags */
1034 map_doc, /* tp_doc */
1035 (traverseproc)map_traverse, /* tp_traverse */
1036 0, /* tp_clear */
1037 0, /* tp_richcompare */
1038 0, /* tp_weaklistoffset */
1039 PyObject_SelfIter, /* tp_iter */
1040 (iternextfunc)map_next, /* tp_iternext */
1041 0, /* tp_methods */
1042 0, /* tp_members */
1043 0, /* tp_getset */
1044 0, /* tp_base */
1045 0, /* tp_dict */
1046 0, /* tp_descr_get */
1047 0, /* tp_descr_set */
1048 0, /* tp_dictoffset */
1049 0, /* tp_init */
1050 PyType_GenericAlloc, /* tp_alloc */
1051 map_new, /* tp_new */
1052 PyObject_GC_Del, /* tp_free */
1053};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001054
Guido van Rossum79f25d91997-04-29 20:08:16 +00001055static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001056builtin_next(PyObject *self, PyObject *args)
1057{
1058 PyObject *it, *res;
1059 PyObject *def = NULL;
1060
1061 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1062 return NULL;
1063 if (!PyIter_Check(it)) {
1064 PyErr_Format(PyExc_TypeError,
Georg Brandlaaa63922008-04-30 19:47:01 +00001065 "%.200s object is not an iterator",
1066 it->ob_type->tp_name);
Georg Brandla18af4e2007-04-21 15:47:16 +00001067 return NULL;
1068 }
1069
1070 res = (*it->ob_type->tp_iternext)(it);
Georg Brandlaaa63922008-04-30 19:47:01 +00001071 if (res != NULL) {
1072 return res;
1073 } else if (def != NULL) {
1074 if (PyErr_Occurred()) {
1075 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
Georg Brandla18af4e2007-04-21 15:47:16 +00001076 return NULL;
1077 PyErr_Clear();
Georg Brandla18af4e2007-04-21 15:47:16 +00001078 }
Georg Brandlaaa63922008-04-30 19:47:01 +00001079 Py_INCREF(def);
1080 return def;
1081 } else if (PyErr_Occurred()) {
1082 return NULL;
1083 } else {
1084 PyErr_SetNone(PyExc_StopIteration);
1085 return NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001086 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001087}
1088
1089PyDoc_STRVAR(next_doc,
1090"next(iterator[, default])\n\
1091\n\
1092Return the next item from the iterator. If default is given and the iterator\n\
1093is exhausted, it is returned instead of raising StopIteration.");
1094
1095
1096static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001097builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001098{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001099 PyObject *v;
1100 PyObject *name;
1101 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001102
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001103 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
Guido van Rossum33894be1992-01-27 16:53:09 +00001104 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001105 if (PyObject_SetAttr(v, name, value) != 0)
Guido van Rossum33894be1992-01-27 16:53:09 +00001106 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001107 Py_INCREF(Py_None);
1108 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001109}
1110
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001111PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001112"setattr(object, name, value)\n\
1113\n\
1114Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001115``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001116
1117
Guido van Rossum79f25d91997-04-29 20:08:16 +00001118static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001119builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001120{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001121 PyObject *v;
1122 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001123
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001124 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
Guido van Rossum14144fc1994-08-29 12:53:40 +00001125 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001126 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001127 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001128 Py_INCREF(Py_None);
1129 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001130}
1131
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001132PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001133"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001134\n\
1135Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001136``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001137
1138
Guido van Rossum79f25d91997-04-29 20:08:16 +00001139static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001140builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001141{
Guido van Rossum9bfef441993-03-29 10:43:31 +00001142 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001143
Guido van Rossum79f25d91997-04-29 20:08:16 +00001144 x = PyObject_Hash(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001145 if (x == -1)
1146 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00001147 return PyLong_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001148}
1149
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001150PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001151"hash(object) -> integer\n\
1152\n\
1153Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001154the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001155
1156
Guido van Rossum79f25d91997-04-29 20:08:16 +00001157static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001158builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001159{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001160 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001161}
1162
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001163PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001164"hex(number) -> string\n\
1165\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001166Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001167
1168
Guido van Rossum79f25d91997-04-29 20:08:16 +00001169static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001170builtin_iter(PyObject *self, PyObject *args)
1171{
1172 PyObject *v, *w = NULL;
1173
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001174 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001175 return NULL;
1176 if (w == NULL)
1177 return PyObject_GetIter(v);
1178 if (!PyCallable_Check(v)) {
1179 PyErr_SetString(PyExc_TypeError,
1180 "iter(v, w): v must be callable");
1181 return NULL;
1182 }
1183 return PyCallIter_New(v, w);
1184}
1185
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001186PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001187"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001188iter(callable, sentinel) -> iterator\n\
1189\n\
1190Get an iterator from an object. In the first form, the argument must\n\
1191supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001192In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001193
1194
1195static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001196builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001197{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001198 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001199
Jeremy Hylton03657cf2000-07-12 13:05:33 +00001200 res = PyObject_Size(v);
Guido van Rossum8ea9f4d1998-06-29 22:26:50 +00001201 if (res < 0 && PyErr_Occurred())
1202 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00001203 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001204}
1205
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001206PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001207"len(object) -> integer\n\
1208\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001209Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001210
1211
Guido van Rossum79f25d91997-04-29 20:08:16 +00001212static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001213builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001214{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001215 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001216
Guido van Rossum79f25d91997-04-29 20:08:16 +00001217 d = PyEval_GetLocals();
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001218 Py_XINCREF(d);
Guido van Rossum872537c1995-07-07 22:43:42 +00001219 return d;
1220}
1221
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001222PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001223"locals() -> dictionary\n\
1224\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001225Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001226
1227
Guido van Rossum79f25d91997-04-29 20:08:16 +00001228static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001229min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001230{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001231 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Martin v. Löwisfd39ad42004-08-12 14:42:37 +00001232 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001233
Guido van Rossum79f25d91997-04-29 20:08:16 +00001234 if (PyTuple_Size(args) > 1)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001235 v = args;
Martin v. Löwisfd39ad42004-08-12 14:42:37 +00001236 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
Guido van Rossum3f5da241990-12-20 15:06:42 +00001237 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001238
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001239 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1240 keyfunc = PyDict_GetItemString(kwds, "key");
1241 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001242 PyErr_Format(PyExc_TypeError,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001243 "%s() got an unexpected keyword argument", name);
1244 return NULL;
1245 }
Christian Heimesbbffeb62008-01-24 09:42:52 +00001246 Py_INCREF(keyfunc);
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001247 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001248
Tim Petersc3074532001-05-03 07:00:32 +00001249 it = PyObject_GetIter(v);
Christian Heimesbbffeb62008-01-24 09:42:52 +00001250 if (it == NULL) {
1251 Py_XDECREF(keyfunc);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001252 return NULL;
Christian Heimesbbffeb62008-01-24 09:42:52 +00001253 }
Tim Petersc3074532001-05-03 07:00:32 +00001254
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001255 maxitem = NULL; /* the result */
1256 maxval = NULL; /* the value associated with the result */
Brett Cannon9e635cf2004-12-07 00:25:35 +00001257 while (( item = PyIter_Next(it) )) {
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001258 /* get the value from the key function */
1259 if (keyfunc != NULL) {
1260 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1261 if (val == NULL)
1262 goto Fail_it_item;
1263 }
1264 /* no key function; the value is the item */
1265 else {
1266 val = item;
1267 Py_INCREF(val);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001268 }
Tim Petersc3074532001-05-03 07:00:32 +00001269
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001270 /* maximum value and item are unset; set them */
1271 if (maxval == NULL) {
1272 maxitem = item;
1273 maxval = val;
1274 }
1275 /* maximum value and item are set; update them as necessary */
Guido van Rossum2d951851994-08-29 12:52:16 +00001276 else {
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001277 int cmp = PyObject_RichCompareBool(val, maxval, op);
1278 if (cmp < 0)
1279 goto Fail_it_item_and_val;
1280 else if (cmp > 0) {
1281 Py_DECREF(maxval);
1282 Py_DECREF(maxitem);
1283 maxval = val;
1284 maxitem = item;
Guido van Rossum53451b32001-01-17 15:47:24 +00001285 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001286 else {
1287 Py_DECREF(item);
1288 Py_DECREF(val);
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001289 }
Guido van Rossum2d951851994-08-29 12:52:16 +00001290 }
Guido van Rossum3f5da241990-12-20 15:06:42 +00001291 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001292 if (PyErr_Occurred())
1293 goto Fail_it;
1294 if (maxval == NULL) {
Martin v. Löwisfd39ad42004-08-12 14:42:37 +00001295 PyErr_Format(PyExc_ValueError,
1296 "%s() arg is an empty sequence", name);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001297 assert(maxitem == NULL);
1298 }
1299 else
1300 Py_DECREF(maxval);
Tim Petersc3074532001-05-03 07:00:32 +00001301 Py_DECREF(it);
Christian Heimesbbffeb62008-01-24 09:42:52 +00001302 Py_XDECREF(keyfunc);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001303 return maxitem;
1304
1305Fail_it_item_and_val:
1306 Py_DECREF(val);
1307Fail_it_item:
1308 Py_DECREF(item);
1309Fail_it:
1310 Py_XDECREF(maxval);
1311 Py_XDECREF(maxitem);
1312 Py_DECREF(it);
Christian Heimesbbffeb62008-01-24 09:42:52 +00001313 Py_XDECREF(keyfunc);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001314 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001315}
1316
Guido van Rossum79f25d91997-04-29 20:08:16 +00001317static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001318builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001319{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001320 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001321}
1322
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001323PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001324"min(iterable[, key=func]) -> value\n\
1325min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001326\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001327With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001328With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001329
1330
Guido van Rossum79f25d91997-04-29 20:08:16 +00001331static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001332builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001333{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001334 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001335}
1336
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001337PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001338"max(iterable[, key=func]) -> value\n\
1339max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001340\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001341With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001342With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001343
1344
Guido van Rossum79f25d91997-04-29 20:08:16 +00001345static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001346builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001347{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001348 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001349}
1350
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001351PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001352"oct(number) -> string\n\
1353\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001354Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001355
1356
Guido van Rossum79f25d91997-04-29 20:08:16 +00001357static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001358builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001359{
Guido van Rossum09095f32000-03-10 23:00:52 +00001360 long ord;
Martin v. Löwisd96ee902006-02-16 14:37:16 +00001361 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001362
Christian Heimes72b710a2008-05-26 13:28:38 +00001363 if (PyBytes_Check(obj)) {
1364 size = PyBytes_GET_SIZE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001365 if (size == 1) {
Christian Heimes72b710a2008-05-26 13:28:38 +00001366 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
Christian Heimes217cfd12007-12-02 14:31:20 +00001367 return PyLong_FromLong(ord);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001368 }
Guido van Rossum98f97462007-04-13 03:31:13 +00001369 }
1370 else if (PyUnicode_Check(obj)) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001371 size = PyUnicode_GET_SIZE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001372 if (size == 1) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001373 ord = (long)*PyUnicode_AS_UNICODE(obj);
Christian Heimes217cfd12007-12-02 14:31:20 +00001374 return PyLong_FromLong(ord);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001375 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001376#ifndef Py_UNICODE_WIDE
1377 if (size == 2) {
1378 /* Decode a valid surrogate pair */
1379 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1380 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1381 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1382 0xDC00 <= c1 && c1 <= 0xDFFF) {
1383 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1384 0x00010000);
Christian Heimes217cfd12007-12-02 14:31:20 +00001385 return PyLong_FromLong(ord);
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001386 }
1387 }
1388#endif
Guido van Rossum6f376c42007-05-24 14:31:33 +00001389 }
Christian Heimes9c4756e2008-05-26 13:22:05 +00001390 else if (PyByteArray_Check(obj)) {
Guido van Rossum98f97462007-04-13 03:31:13 +00001391 /* XXX Hopefully this is temporary */
Christian Heimes9c4756e2008-05-26 13:22:05 +00001392 size = PyByteArray_GET_SIZE(obj);
Guido van Rossum98f97462007-04-13 03:31:13 +00001393 if (size == 1) {
Christian Heimes9c4756e2008-05-26 13:22:05 +00001394 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
Christian Heimes217cfd12007-12-02 14:31:20 +00001395 return PyLong_FromLong(ord);
Guido van Rossum98f97462007-04-13 03:31:13 +00001396 }
1397 }
1398 else {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001399 PyErr_Format(PyExc_TypeError,
Andrew M. Kuchlingf07aad12000-12-23 14:11:28 +00001400 "ord() expected string of length 1, but " \
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001401 "%.200s found", obj->ob_type->tp_name);
Guido van Rossum09095f32000-03-10 23:00:52 +00001402 return NULL;
1403 }
1404
Guido van Rossumad991772001-01-12 16:03:05 +00001405 PyErr_Format(PyExc_TypeError,
Andrew M. Kuchlingf07aad12000-12-23 14:11:28 +00001406 "ord() expected a character, "
Martin v. Löwisd96ee902006-02-16 14:37:16 +00001407 "but string of length %zd found",
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001408 size);
1409 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001410}
1411
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001412PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001413"ord(c) -> integer\n\
1414\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001415Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001416)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001417#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001418PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001419"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001420)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001421#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001422;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001423
1424
Guido van Rossum79f25d91997-04-29 20:08:16 +00001425static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001426builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001427{
Guido van Rossum09df08a1998-05-22 00:51:39 +00001428 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001429
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001430 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001431 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +00001432 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001433}
1434
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001435PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001436"pow(x, y[, z]) -> number\n\
1437\n\
1438With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001439equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001440
1441
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001442
Guido van Rossum34343512006-11-30 22:13:52 +00001443static PyObject *
1444builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1445{
1446 static char *kwlist[] = {"sep", "end", "file", 0};
Georg Brandl257d3d92007-02-26 10:35:10 +00001447 static PyObject *dummy_args;
Guido van Rossum34343512006-11-30 22:13:52 +00001448 PyObject *sep = NULL, *end = NULL, *file = NULL;
1449 int i, err;
1450
Georg Brandl257d3d92007-02-26 10:35:10 +00001451 if (dummy_args == NULL) {
1452 if (!(dummy_args = PyTuple_New(0)))
1453 return NULL;
1454 }
Georg Brandl88fc6642007-02-09 21:28:07 +00001455 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
Guido van Rossum34343512006-11-30 22:13:52 +00001456 kwlist, &sep, &end, &file))
Christian Heimesfef9bba2007-11-13 15:24:14 +00001457 return NULL;
1458 if (file == NULL || file == Py_None) {
Guido van Rossum34343512006-11-30 22:13:52 +00001459 file = PySys_GetObject("stdout");
Christian Heimesfef9bba2007-11-13 15:24:14 +00001460 /* sys.stdout may be None when FILE* stdout isn't connected */
1461 if (file == Py_None)
1462 Py_RETURN_NONE;
1463 }
Guido van Rossum34343512006-11-30 22:13:52 +00001464
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001465 if (sep && sep != Py_None && !PyUnicode_Check(sep)) {
Georg Brandl16f3e032006-11-30 22:46:03 +00001466 PyErr_Format(PyExc_TypeError,
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001467 "sep must be None or a string, not %.200s",
Georg Brandl16f3e032006-11-30 22:46:03 +00001468 sep->ob_type->tp_name);
1469 return NULL;
1470 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001471 if (end && end != Py_None && !PyUnicode_Check(end)) {
Georg Brandl16f3e032006-11-30 22:46:03 +00001472 PyErr_Format(PyExc_TypeError,
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001473 "end must be None or a string, not %.200s",
Georg Brandl16f3e032006-11-30 22:46:03 +00001474 end->ob_type->tp_name);
1475 return NULL;
1476 }
Guido van Rossum34343512006-11-30 22:13:52 +00001477
1478 for (i = 0; i < PyTuple_Size(args); i++) {
1479 if (i > 0) {
1480 if (sep == NULL || sep == Py_None)
1481 err = PyFile_WriteString(" ", file);
1482 else
1483 err = PyFile_WriteObject(sep, file,
1484 Py_PRINT_RAW);
1485 if (err)
1486 return NULL;
1487 }
1488 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1489 Py_PRINT_RAW);
1490 if (err)
1491 return NULL;
1492 }
1493
1494 if (end == NULL || end == Py_None)
1495 err = PyFile_WriteString("\n", file);
1496 else
1497 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1498 if (err)
1499 return NULL;
1500
1501 Py_RETURN_NONE;
1502}
1503
1504PyDoc_STRVAR(print_doc,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001505"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001506\n\
1507Prints the values to a stream, or to sys.stdout by default.\n\
1508Optional keyword arguments:\n\
1509file: a file-like object (stream); defaults to the current sys.stdout.\n\
1510sep: string inserted between values, default a space.\n\
1511end: string appended after the last value, default a newline.");
1512
1513
Guido van Rossuma88a0332007-02-26 16:59:55 +00001514static PyObject *
1515builtin_input(PyObject *self, PyObject *args)
1516{
Guido van Rossumeba76962007-05-27 09:13:28 +00001517 PyObject *promptarg = NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001518 PyObject *fin = PySys_GetObject("stdin");
1519 PyObject *fout = PySys_GetObject("stdout");
Guido van Rossumeba76962007-05-27 09:13:28 +00001520 PyObject *ferr = PySys_GetObject("stderr");
1521 PyObject *tmp;
1522 long fd;
1523 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001524
Guido van Rossumeba76962007-05-27 09:13:28 +00001525 /* Parse arguments */
1526 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
Guido van Rossuma88a0332007-02-26 16:59:55 +00001527 return NULL;
1528
Guido van Rossumeba76962007-05-27 09:13:28 +00001529 /* Check that stdin/out/err are intact */
Christian Heimes2be03732007-11-15 02:26:46 +00001530 if (fin == NULL || fin == Py_None) {
Guido van Rossumeba76962007-05-27 09:13:28 +00001531 PyErr_SetString(PyExc_RuntimeError,
1532 "input(): lost sys.stdin");
Guido van Rossuma88a0332007-02-26 16:59:55 +00001533 return NULL;
1534 }
Christian Heimes2be03732007-11-15 02:26:46 +00001535 if (fout == NULL || fout == Py_None) {
Guido van Rossumeba76962007-05-27 09:13:28 +00001536 PyErr_SetString(PyExc_RuntimeError,
1537 "input(): lost sys.stdout");
Guido van Rossuma88a0332007-02-26 16:59:55 +00001538 return NULL;
1539 }
Christian Heimes2be03732007-11-15 02:26:46 +00001540 if (ferr == NULL || ferr == Py_None) {
Guido van Rossumeba76962007-05-27 09:13:28 +00001541 PyErr_SetString(PyExc_RuntimeError,
1542 "input(): lost sys.stderr");
1543 return NULL;
1544 }
1545
1546 /* First of all, flush stderr */
1547 tmp = PyObject_CallMethod(ferr, "flush", "");
1548 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001549 PyErr_Clear();
1550 else
1551 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001552
1553 /* We should only use (GNU) readline if Python's sys.stdin and
1554 sys.stdout are the same as C's stdin and stdout, because we
1555 need to pass it those. */
1556 tmp = PyObject_CallMethod(fin, "fileno", "");
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001557 if (tmp == NULL) {
1558 PyErr_Clear();
1559 tty = 0;
1560 }
1561 else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001562 fd = PyLong_AsLong(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001563 Py_DECREF(tmp);
1564 if (fd < 0 && PyErr_Occurred())
1565 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001566 tty = fd == fileno(stdin) && isatty(fd);
1567 }
1568 if (tty) {
1569 tmp = PyObject_CallMethod(fout, "fileno", "");
1570 if (tmp == NULL)
1571 PyErr_Clear();
1572 else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001573 fd = PyLong_AsLong(tmp);
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001574 Py_DECREF(tmp);
1575 if (fd < 0 && PyErr_Occurred())
1576 return NULL;
1577 tty = fd == fileno(stdout) && isatty(fd);
1578 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001579 }
1580
1581 /* If we're interactive, use (GNU) readline */
1582 if (tty) {
Guido van Rossuma88a0332007-02-26 16:59:55 +00001583 PyObject *po;
1584 char *prompt;
1585 char *s;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001586 PyObject *stdin_encoding;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001587 PyObject *result;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001588
1589 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1590 if (!stdin_encoding)
1591 /* stdin is a text stream, so it must have an
1592 encoding. */
1593 return NULL;
Guido van Rossumeba76962007-05-27 09:13:28 +00001594 tmp = PyObject_CallMethod(fout, "flush", "");
1595 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001596 PyErr_Clear();
1597 else
1598 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001599 if (promptarg != NULL) {
1600 po = PyObject_Str(promptarg);
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001601 if (po == NULL) {
1602 Py_DECREF(stdin_encoding);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001603 return NULL;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001604 }
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001605 prompt = _PyUnicode_AsString(po);
Guido van Rossumeba76962007-05-27 09:13:28 +00001606 if (prompt == NULL) {
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001607 Py_DECREF(stdin_encoding);
Guido van Rossumeba76962007-05-27 09:13:28 +00001608 Py_DECREF(po);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001609 return NULL;
Guido van Rossumeba76962007-05-27 09:13:28 +00001610 }
Guido van Rossuma88a0332007-02-26 16:59:55 +00001611 }
1612 else {
1613 po = NULL;
1614 prompt = "";
1615 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001616 s = PyOS_Readline(stdin, stdout, prompt);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001617 Py_XDECREF(po);
1618 if (s == NULL) {
1619 if (!PyErr_Occurred())
1620 PyErr_SetNone(PyExc_KeyboardInterrupt);
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001621 Py_DECREF(stdin_encoding);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001622 return NULL;
1623 }
1624 if (*s == '\0') {
1625 PyErr_SetNone(PyExc_EOFError);
1626 result = NULL;
1627 }
1628 else { /* strip trailing '\n' */
1629 size_t len = strlen(s);
1630 if (len > PY_SSIZE_T_MAX) {
1631 PyErr_SetString(PyExc_OverflowError,
1632 "input: input too long");
1633 result = NULL;
1634 }
1635 else {
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001636 result = PyUnicode_Decode
1637 (s, len-1,
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001638 _PyUnicode_AsString(stdin_encoding),
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001639 NULL);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001640 }
1641 }
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001642 Py_DECREF(stdin_encoding);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001643 PyMem_FREE(s);
1644 return result;
1645 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001646
1647 /* Fallback if we're not interactive */
1648 if (promptarg != NULL) {
1649 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
Guido van Rossuma88a0332007-02-26 16:59:55 +00001650 return NULL;
1651 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001652 tmp = PyObject_CallMethod(fout, "flush", "");
1653 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001654 PyErr_Clear();
1655 else
1656 Py_DECREF(tmp);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001657 return PyFile_GetLine(fin, -1);
1658}
1659
1660PyDoc_STRVAR(input_doc,
1661"input([prompt]) -> string\n\
1662\n\
1663Read a string from standard input. The trailing newline is stripped.\n\
1664If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1665On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1666is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001667
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001668
Guido van Rossum79f25d91997-04-29 20:08:16 +00001669static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001670builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001671{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001672 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001673}
1674
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001675PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001676"repr(object) -> string\n\
1677\n\
1678Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001679For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001680
1681
Guido van Rossum79f25d91997-04-29 20:08:16 +00001682static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001683builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001684{
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001685#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
1686 static PyObject *round_str = NULL;
1687 int ndigits = UNDEF_NDIGITS;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001688 static char *kwlist[] = {"number", "ndigits", 0};
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001689 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001690
Alex Martelliae211f92007-08-22 23:21:33 +00001691 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|i:round",
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001692 kwlist, &number, &ndigits))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001693 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001694
Christian Heimes90aa7642007-12-19 02:45:37 +00001695 if (Py_TYPE(number)->tp_dict == NULL) {
1696 if (PyType_Ready(Py_TYPE(number)) < 0)
Guido van Rossum15d3d042007-08-24 02:02:45 +00001697 return NULL;
1698 }
1699
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001700 if (round_str == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +00001701 round_str = PyUnicode_InternFromString("__round__");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001702 if (round_str == NULL)
Alex Martelliae211f92007-08-22 23:21:33 +00001703 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001704 }
1705
Christian Heimes90aa7642007-12-19 02:45:37 +00001706 round = _PyType_Lookup(Py_TYPE(number), round_str);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001707 if (round == NULL) {
1708 PyErr_Format(PyExc_TypeError,
1709 "type %.100s doesn't define __round__ method",
Christian Heimes90aa7642007-12-19 02:45:37 +00001710 Py_TYPE(number)->tp_name);
Alex Martelliae211f92007-08-22 23:21:33 +00001711 return NULL;
1712 }
1713
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001714 if (ndigits == UNDEF_NDIGITS)
1715 return PyObject_CallFunction(round, "O", number);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001716 else
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001717 return PyObject_CallFunction(round, "Oi", number, ndigits);
1718#undef UNDEF_NDIGITS
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001719}
1720
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001721PyDoc_STRVAR(round_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001722"round(number[, ndigits]) -> floating point number\n\
1723\n\
1724Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001725This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001726same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001727
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001728
Raymond Hettinger64958a12003-12-17 20:43:33 +00001729static PyObject *
1730builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1731{
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001732 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001733 PyObject *callable;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001734 static char *kwlist[] = {"iterable", "key", "reverse", 0};
Neal Norwitz6f0d4792005-12-15 06:40:36 +00001735 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001736
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001737 /* args 1-3 should match listsort in Objects/listobject.c */
1738 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1739 kwlist, &seq, &keyfunc, &reverse))
Armin Rigo71d7e702005-09-20 18:13:03 +00001740 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001741
1742 newlist = PySequence_List(seq);
1743 if (newlist == NULL)
1744 return NULL;
1745
1746 callable = PyObject_GetAttrString(newlist, "sort");
1747 if (callable == NULL) {
1748 Py_DECREF(newlist);
1749 return NULL;
1750 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001751
Raymond Hettinger64958a12003-12-17 20:43:33 +00001752 newargs = PyTuple_GetSlice(args, 1, 4);
1753 if (newargs == NULL) {
1754 Py_DECREF(newlist);
1755 Py_DECREF(callable);
1756 return NULL;
1757 }
1758
1759 v = PyObject_Call(callable, newargs, kwds);
1760 Py_DECREF(newargs);
1761 Py_DECREF(callable);
1762 if (v == NULL) {
1763 Py_DECREF(newlist);
1764 return NULL;
1765 }
1766 Py_DECREF(v);
1767 return newlist;
1768}
1769
1770PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001771"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001772
Guido van Rossum79f25d91997-04-29 20:08:16 +00001773static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001774builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001775{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001776 PyObject *v = NULL;
1777 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001778
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001779 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001780 return NULL;
Guido van Rossum2d951851994-08-29 12:52:16 +00001781 if (v == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001782 d = PyEval_GetLocals();
Guido van Rossum53bb7ff1995-07-26 16:26:31 +00001783 if (d == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001784 if (!PyErr_Occurred())
1785 PyErr_SetString(PyExc_SystemError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +00001786 "vars(): no locals!?");
Guido van Rossum53bb7ff1995-07-26 16:26:31 +00001787 }
1788 else
Guido van Rossum79f25d91997-04-29 20:08:16 +00001789 Py_INCREF(d);
Guido van Rossum2d951851994-08-29 12:52:16 +00001790 }
1791 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001792 d = PyObject_GetAttrString(v, "__dict__");
Guido van Rossum2d951851994-08-29 12:52:16 +00001793 if (d == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001794 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2d951851994-08-29 12:52:16 +00001795 "vars() argument must have __dict__ attribute");
1796 return NULL;
1797 }
1798 }
1799 return d;
1800}
1801
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001802PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001803"vars([object]) -> dictionary\n\
1804\n\
1805Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001806With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001807
Alex Martellia70b1912003-04-22 08:12:33 +00001808static PyObject*
1809builtin_sum(PyObject *self, PyObject *args)
1810{
1811 PyObject *seq;
1812 PyObject *result = NULL;
1813 PyObject *temp, *item, *iter;
1814
Raymond Hettinger5cf63942003-10-25 06:41:37 +00001815 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
Alex Martellia70b1912003-04-22 08:12:33 +00001816 return NULL;
1817
1818 iter = PyObject_GetIter(seq);
1819 if (iter == NULL)
1820 return NULL;
1821
1822 if (result == NULL) {
Christian Heimes217cfd12007-12-02 14:31:20 +00001823 result = PyLong_FromLong(0);
Alex Martellia70b1912003-04-22 08:12:33 +00001824 if (result == NULL) {
1825 Py_DECREF(iter);
1826 return NULL;
1827 }
1828 } else {
1829 /* reject string values for 'start' parameter */
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001830 if (PyUnicode_Check(result)) {
Alex Martellia70b1912003-04-22 08:12:33 +00001831 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +00001832 "sum() can't sum strings [use ''.join(seq) instead]");
Alex Martellia70b1912003-04-22 08:12:33 +00001833 Py_DECREF(iter);
1834 return NULL;
1835 }
Christian Heimes9c4756e2008-05-26 13:22:05 +00001836 if (PyByteArray_Check(result)) {
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001837 PyErr_SetString(PyExc_TypeError,
1838 "sum() can't sum bytes [use b''.join(seq) instead]");
1839 Py_DECREF(iter);
1840 return NULL;
1841 }
1842
Alex Martelli41c9f882003-04-22 09:24:48 +00001843 Py_INCREF(result);
Alex Martellia70b1912003-04-22 08:12:33 +00001844 }
1845
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001846#ifndef SLOW_SUM
1847 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1848 Assumes all inputs are the same type. If the assumption fails, default
1849 to the more general routine.
1850 */
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001851 if (PyLong_CheckExact(result)) {
1852 int overflow;
1853 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1854 /* If this already overflowed, don't even enter the loop. */
1855 if (overflow == 0) {
1856 Py_DECREF(result);
1857 result = NULL;
1858 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001859 while(result == NULL) {
1860 item = PyIter_Next(iter);
1861 if (item == NULL) {
1862 Py_DECREF(iter);
1863 if (PyErr_Occurred())
1864 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00001865 return PyLong_FromLong(i_result);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001866 }
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001867 if (PyLong_CheckExact(item)) {
1868 long b = PyLong_AsLongAndOverflow(item, &overflow);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001869 long x = i_result + b;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001870 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001871 i_result = x;
1872 Py_DECREF(item);
1873 continue;
1874 }
1875 }
1876 /* Either overflowed or is not an int. Restore real objects and process normally */
Christian Heimes217cfd12007-12-02 14:31:20 +00001877 result = PyLong_FromLong(i_result);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001878 temp = PyNumber_Add(result, item);
1879 Py_DECREF(result);
1880 Py_DECREF(item);
1881 result = temp;
1882 if (result == NULL) {
1883 Py_DECREF(iter);
1884 return NULL;
1885 }
1886 }
1887 }
1888
1889 if (PyFloat_CheckExact(result)) {
1890 double f_result = PyFloat_AS_DOUBLE(result);
1891 Py_DECREF(result);
1892 result = NULL;
1893 while(result == NULL) {
1894 item = PyIter_Next(iter);
1895 if (item == NULL) {
1896 Py_DECREF(iter);
1897 if (PyErr_Occurred())
1898 return NULL;
1899 return PyFloat_FromDouble(f_result);
1900 }
1901 if (PyFloat_CheckExact(item)) {
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001902 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001903 f_result += PyFloat_AS_DOUBLE(item);
1904 PyFPE_END_PROTECT(f_result)
1905 Py_DECREF(item);
1906 continue;
1907 }
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001908 if (PyLong_CheckExact(item)) {
1909 long value;
1910 int overflow;
1911 value = PyLong_AsLongAndOverflow(item, &overflow);
1912 if (!overflow) {
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001913 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001914 f_result += (double)value;
1915 PyFPE_END_PROTECT(f_result)
1916 Py_DECREF(item);
1917 continue;
1918 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001919 }
1920 result = PyFloat_FromDouble(f_result);
1921 temp = PyNumber_Add(result, item);
1922 Py_DECREF(result);
1923 Py_DECREF(item);
1924 result = temp;
1925 if (result == NULL) {
1926 Py_DECREF(iter);
1927 return NULL;
1928 }
1929 }
1930 }
1931#endif
1932
Alex Martellia70b1912003-04-22 08:12:33 +00001933 for(;;) {
1934 item = PyIter_Next(iter);
1935 if (item == NULL) {
1936 /* error, or end-of-sequence */
1937 if (PyErr_Occurred()) {
1938 Py_DECREF(result);
1939 result = NULL;
1940 }
1941 break;
1942 }
Alex Martellia253e182003-10-25 23:24:14 +00001943 temp = PyNumber_Add(result, item);
Alex Martellia70b1912003-04-22 08:12:33 +00001944 Py_DECREF(result);
1945 Py_DECREF(item);
1946 result = temp;
1947 if (result == NULL)
1948 break;
1949 }
1950 Py_DECREF(iter);
1951 return result;
1952}
1953
1954PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001955"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00001956\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00001957Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
1958of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00001959empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00001960
1961
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001962static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001963builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001964{
1965 PyObject *inst;
1966 PyObject *cls;
Guido van Rossum823649d2001-03-21 18:40:58 +00001967 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001968
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001969 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001970 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00001971
Guido van Rossum823649d2001-03-21 18:40:58 +00001972 retval = PyObject_IsInstance(inst, cls);
1973 if (retval < 0)
Guido van Rossumad991772001-01-12 16:03:05 +00001974 return NULL;
Guido van Rossum77f6a652002-04-03 22:41:51 +00001975 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001976}
1977
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001978PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00001979"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001980\n\
1981Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00001982With a type as second argument, return whether that is the object's type.\n\
1983The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001984isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001985
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001986
1987static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001988builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001989{
1990 PyObject *derived;
1991 PyObject *cls;
1992 int retval;
1993
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001994 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001995 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00001996
Guido van Rossum823649d2001-03-21 18:40:58 +00001997 retval = PyObject_IsSubclass(derived, cls);
1998 if (retval < 0)
1999 return NULL;
Guido van Rossum77f6a652002-04-03 22:41:51 +00002000 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002001}
2002
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002003PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002004"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002005\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002006Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2007When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2008is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002009
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002010
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002011typedef struct {
2012 PyObject_HEAD
2013 Py_ssize_t tuplesize;
2014 PyObject *ittuple; /* tuple of iterators */
2015 PyObject *result;
2016} zipobject;
2017
2018PyTypeObject PyZip_Type;
2019
2020static PyObject *
2021zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002022{
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002023 zipobject *lz;
2024 Py_ssize_t i;
2025 PyObject *ittuple; /* tuple of iterators */
2026 PyObject *result;
2027 Py_ssize_t tuplesize = PySequence_Length(args);
2028
2029 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2030 return NULL;
2031
Guido van Rossumb65fb332006-08-25 23:26:40 +00002032 /* args must be a tuple */
2033 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002034
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002035 /* obtain iterators */
2036 ittuple = PyTuple_New(tuplesize);
2037 if (ittuple == NULL)
2038 return NULL;
2039 for (i=0; i < tuplesize; ++i) {
2040 PyObject *item = PyTuple_GET_ITEM(args, i);
2041 PyObject *it = PyObject_GetIter(item);
2042 if (it == NULL) {
2043 if (PyErr_ExceptionMatches(PyExc_TypeError))
2044 PyErr_Format(PyExc_TypeError,
2045 "zip argument #%zd must support iteration",
2046 i+1);
2047 Py_DECREF(ittuple);
2048 return NULL;
2049 }
2050 PyTuple_SET_ITEM(ittuple, i, it);
2051 }
2052
2053 /* create a result holder */
2054 result = PyTuple_New(tuplesize);
2055 if (result == NULL) {
2056 Py_DECREF(ittuple);
2057 return NULL;
2058 }
2059 for (i=0 ; i < tuplesize ; i++) {
2060 Py_INCREF(Py_None);
2061 PyTuple_SET_ITEM(result, i, Py_None);
2062 }
2063
2064 /* create zipobject structure */
2065 lz = (zipobject *)type->tp_alloc(type, 0);
2066 if (lz == NULL) {
2067 Py_DECREF(ittuple);
2068 Py_DECREF(result);
2069 return NULL;
2070 }
2071 lz->ittuple = ittuple;
2072 lz->tuplesize = tuplesize;
2073 lz->result = result;
2074
2075 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002076}
2077
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002078static void
2079zip_dealloc(zipobject *lz)
2080{
2081 PyObject_GC_UnTrack(lz);
2082 Py_XDECREF(lz->ittuple);
2083 Py_XDECREF(lz->result);
2084 Py_TYPE(lz)->tp_free(lz);
2085}
2086
2087static int
2088zip_traverse(zipobject *lz, visitproc visit, void *arg)
2089{
2090 Py_VISIT(lz->ittuple);
2091 Py_VISIT(lz->result);
2092 return 0;
2093}
2094
2095static PyObject *
2096zip_next(zipobject *lz)
2097{
2098 Py_ssize_t i;
2099 Py_ssize_t tuplesize = lz->tuplesize;
2100 PyObject *result = lz->result;
2101 PyObject *it;
2102 PyObject *item;
2103 PyObject *olditem;
2104
2105 if (tuplesize == 0)
2106 return NULL;
2107 if (Py_REFCNT(result) == 1) {
2108 Py_INCREF(result);
2109 for (i=0 ; i < tuplesize ; i++) {
2110 it = PyTuple_GET_ITEM(lz->ittuple, i);
2111 assert(PyIter_Check(it));
2112 item = (*Py_TYPE(it)->tp_iternext)(it);
2113 if (item == NULL) {
2114 Py_DECREF(result);
2115 return NULL;
2116 }
2117 olditem = PyTuple_GET_ITEM(result, i);
2118 PyTuple_SET_ITEM(result, i, item);
2119 Py_DECREF(olditem);
2120 }
2121 } else {
2122 result = PyTuple_New(tuplesize);
2123 if (result == NULL)
2124 return NULL;
2125 for (i=0 ; i < tuplesize ; i++) {
2126 it = PyTuple_GET_ITEM(lz->ittuple, i);
2127 assert(PyIter_Check(it));
2128 item = (*Py_TYPE(it)->tp_iternext)(it);
2129 if (item == NULL) {
2130 Py_DECREF(result);
2131 return NULL;
2132 }
2133 PyTuple_SET_ITEM(result, i, item);
2134 }
2135 }
2136 return result;
2137}
Barry Warsawbd599b52000-08-03 15:45:29 +00002138
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002139PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002140"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002141\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002142Return a zip object whose .__next__() method returns a tuple where\n\
2143the i-th element comes from the i-th iterable argument. The .__next__()\n\
2144method continues until the shortest iterable in the argument sequence\n\
2145is exhausted and then it raises StopIteration. Works like the zip()\n\
2146function but consumes less memory by returning an iterator instead of\n\
2147a list.");
2148
2149PyTypeObject PyZip_Type = {
2150 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2151 "zip", /* tp_name */
2152 sizeof(zipobject), /* tp_basicsize */
2153 0, /* tp_itemsize */
2154 /* methods */
2155 (destructor)zip_dealloc, /* tp_dealloc */
2156 0, /* tp_print */
2157 0, /* tp_getattr */
2158 0, /* tp_setattr */
2159 0, /* tp_compare */
2160 0, /* tp_repr */
2161 0, /* tp_as_number */
2162 0, /* tp_as_sequence */
2163 0, /* tp_as_mapping */
2164 0, /* tp_hash */
2165 0, /* tp_call */
2166 0, /* tp_str */
2167 PyObject_GenericGetAttr, /* tp_getattro */
2168 0, /* tp_setattro */
2169 0, /* tp_as_buffer */
2170 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2171 Py_TPFLAGS_BASETYPE, /* tp_flags */
2172 zip_doc, /* tp_doc */
2173 (traverseproc)zip_traverse, /* tp_traverse */
2174 0, /* tp_clear */
2175 0, /* tp_richcompare */
2176 0, /* tp_weaklistoffset */
2177 PyObject_SelfIter, /* tp_iter */
2178 (iternextfunc)zip_next, /* tp_iternext */
2179 0, /* tp_methods */
2180 0, /* tp_members */
2181 0, /* tp_getset */
2182 0, /* tp_base */
2183 0, /* tp_dict */
2184 0, /* tp_descr_get */
2185 0, /* tp_descr_set */
2186 0, /* tp_dictoffset */
2187 0, /* tp_init */
2188 PyType_GenericAlloc, /* tp_alloc */
2189 zip_new, /* tp_new */
2190 PyObject_GC_Del, /* tp_free */
2191};
Barry Warsawbd599b52000-08-03 15:45:29 +00002192
2193
Guido van Rossum79f25d91997-04-29 20:08:16 +00002194static PyMethodDef builtin_methods[] = {
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002195 {"__build_class__", (PyCFunction)builtin___build_class__,
2196 METH_VARARGS | METH_KEYWORDS, build_class_doc},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002197 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002198 {"abs", builtin_abs, METH_O, abs_doc},
Raymond Hettinger96229b12005-03-11 06:49:40 +00002199 {"all", builtin_all, METH_O, all_doc},
2200 {"any", builtin_any, METH_O, any_doc},
Georg Brandl559e5d72008-06-11 18:37:52 +00002201 {"ascii", builtin_ascii, METH_O, ascii_doc},
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002202 {"bin", builtin_bin, METH_O, bin_doc},
Neal Norwitzc2550c72007-08-31 04:17:51 +00002203 {"chr", builtin_chr, METH_VARARGS, chr_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002204 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
Guido van Rossumd8faa362007-04-27 19:54:29 +00002205 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002206 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2207 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2208 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2209 {"eval", builtin_eval, METH_VARARGS, eval_doc},
Georg Brandl7cae87c2006-09-06 06:51:57 +00002210 {"exec", builtin_exec, METH_VARARGS, exec_doc},
Eric Smith8c663262007-08-25 02:26:07 +00002211 {"format", builtin_format, METH_VARARGS, format_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002212 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2213 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2214 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2215 {"hash", builtin_hash, METH_O, hash_doc},
2216 {"hex", builtin_hex, METH_O, hex_doc},
2217 {"id", builtin_id, METH_O, id_doc},
Guido van Rossuma88a0332007-02-26 16:59:55 +00002218 {"input", builtin_input, METH_VARARGS, input_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002219 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2220 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2221 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2222 {"len", builtin_len, METH_O, len_doc},
2223 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00002224 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2225 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
Georg Brandla18af4e2007-04-21 15:47:16 +00002226 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002227 {"oct", builtin_oct, METH_O, oct_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002228 {"ord", builtin_ord, METH_O, ord_doc},
2229 {"pow", builtin_pow, METH_VARARGS, pow_doc},
Guido van Rossum452bf512007-02-09 05:32:43 +00002230 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002231 {"repr", builtin_repr, METH_O, repr_doc},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002232 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002233 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
Raymond Hettinger64958a12003-12-17 20:43:33 +00002234 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
Alex Martellia70b1912003-04-22 08:12:33 +00002235 {"sum", builtin_sum, METH_VARARGS, sum_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002236 {"vars", builtin_vars, METH_VARARGS, vars_doc},
Guido van Rossumc02e15c1991-12-16 13:03:00 +00002237 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002238};
2239
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002240PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002241"Built-in functions, exceptions, and other objects.\n\
2242\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002243Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002244
Martin v. Löwis1a214512008-06-11 05:26:20 +00002245static struct PyModuleDef builtinsmodule = {
2246 PyModuleDef_HEAD_INIT,
2247 "builtins",
2248 builtin_doc,
2249 0,
2250 builtin_methods,
2251 NULL,
2252 NULL,
2253 NULL,
2254 NULL
2255};
2256
2257
Guido van Rossum25ce5661997-08-02 03:10:38 +00002258PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002259_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002260{
Fred Drake5550de32000-06-20 04:54:19 +00002261 PyObject *mod, *dict, *debug;
Martin v. Löwis1a214512008-06-11 05:26:20 +00002262 mod = PyModule_Create(&builtinsmodule);
Guido van Rossum25ce5661997-08-02 03:10:38 +00002263 if (mod == NULL)
2264 return NULL;
2265 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002266
Tim Peters7571a0f2003-03-23 17:52:28 +00002267#ifdef Py_TRACE_REFS
Georg Brandl1a3284e2007-12-02 09:40:06 +00002268 /* "builtins" exposes a number of statically allocated objects
Tim Peters7571a0f2003-03-23 17:52:28 +00002269 * that, before this code was added in 2.3, never showed up in
2270 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2271 * result, programs leaking references to None and False (etc)
2272 * couldn't be diagnosed by examining sys.getobjects(0).
2273 */
2274#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2275#else
2276#define ADD_TO_ALL(OBJECT) (void)0
2277#endif
2278
Tim Peters4b7625e2001-09-13 21:37:17 +00002279#define SETBUILTIN(NAME, OBJECT) \
Tim Peters7571a0f2003-03-23 17:52:28 +00002280 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2281 return NULL; \
2282 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002283
2284 SETBUILTIN("None", Py_None);
2285 SETBUILTIN("Ellipsis", Py_Ellipsis);
2286 SETBUILTIN("NotImplemented", Py_NotImplemented);
Guido van Rossum77f6a652002-04-03 22:41:51 +00002287 SETBUILTIN("False", Py_False);
2288 SETBUILTIN("True", Py_True);
2289 SETBUILTIN("bool", &PyBool_Type);
Guido van Rossumbae07c92007-10-08 02:46:15 +00002290 SETBUILTIN("memoryview", &PyMemoryView_Type);
Christian Heimes9c4756e2008-05-26 13:22:05 +00002291 SETBUILTIN("bytearray", &PyByteArray_Type);
Christian Heimes72b710a2008-05-26 13:28:38 +00002292 SETBUILTIN("bytes", &PyBytes_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00002293 SETBUILTIN("classmethod", &PyClassMethod_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002294#ifndef WITHOUT_COMPLEX
Tim Peters4b7625e2001-09-13 21:37:17 +00002295 SETBUILTIN("complex", &PyComplex_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002296#endif
Tim Petersa427a2b2001-10-29 22:25:45 +00002297 SETBUILTIN("dict", &PyDict_Type);
Tim Peters67d687a2002-04-29 21:27:32 +00002298 SETBUILTIN("enumerate", &PyEnum_Type);
Raymond Hettinger17301e92008-03-13 00:19:26 +00002299 SETBUILTIN("filter", &PyFilter_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00002300 SETBUILTIN("float", &PyFloat_Type);
Raymond Hettingera690a992003-11-16 16:17:49 +00002301 SETBUILTIN("frozenset", &PyFrozenSet_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00002302 SETBUILTIN("property", &PyProperty_Type);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002303 SETBUILTIN("int", &PyLong_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00002304 SETBUILTIN("list", &PyList_Type);
Raymond Hettingera6c60372008-03-13 01:26:19 +00002305 SETBUILTIN("map", &PyMap_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00002306 SETBUILTIN("object", &PyBaseObject_Type);
Guido van Rossum805365e2007-05-07 22:24:25 +00002307 SETBUILTIN("range", &PyRange_Type);
Raymond Hettinger85c20a42003-11-06 14:06:48 +00002308 SETBUILTIN("reversed", &PyReversed_Type);
Raymond Hettingera690a992003-11-16 16:17:49 +00002309 SETBUILTIN("set", &PySet_Type);
Guido van Rossumbea18cc2002-06-14 20:41:17 +00002310 SETBUILTIN("slice", &PySlice_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00002311 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
Guido van Rossum572dbf82007-04-27 23:53:51 +00002312 SETBUILTIN("str", &PyUnicode_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00002313 SETBUILTIN("super", &PySuper_Type);
2314 SETBUILTIN("tuple", &PyTuple_Type);
2315 SETBUILTIN("type", &PyType_Type);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002316 SETBUILTIN("zip", &PyZip_Type);
Guido van Rossum77f6a652002-04-03 22:41:51 +00002317 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
Fred Drake5550de32000-06-20 04:54:19 +00002318 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2319 Py_XDECREF(debug);
Guido van Rossum25ce5661997-08-02 03:10:38 +00002320 return NULL;
Fred Drake5550de32000-06-20 04:54:19 +00002321 }
2322 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002323
Guido van Rossum25ce5661997-08-02 03:10:38 +00002324 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002325#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002326#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002327}