blob: 94b2798fee476a2dcd54529ea3124bb54247db2a [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 Rossum3f5da241990-12-20 15:06:42 +00008
Guido van Rossum6bf62da1997-04-11 20:37:35 +00009#include <ctype.h>
10
Victor Stinnerb744ba12010-05-15 12:27:16 +000011#ifdef HAVE_LANGINFO_H
12#include <langinfo.h> /* CODESET */
13#endif
14
Mark Hammond26cffde42001-05-14 12:17:34 +000015/* The default encoding used by the platform file system APIs
16 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000017
18 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
19 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000020*/
Victor Stinner99b95382011-07-04 14:23:54 +020021#ifdef HAVE_MBCS
Mark Hammond26cffde42001-05-14 12:17:34 +000022const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000023int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000024#elif defined(__APPLE__)
25const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerd64e8a72011-07-04 13:48:30 +020027#else
Victor Stinnerb744ba12010-05-15 12:27:16 +000028const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000030#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000031
Guido van Rossum79f25d91997-04-29 20:08:16 +000032static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000033builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
34{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000035 PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell;
36 PyObject *cls = NULL;
Brett Cannonb94767f2011-02-22 20:15:44 +000037 Py_ssize_t nargs;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 assert(args != NULL);
40 if (!PyTuple_Check(args)) {
41 PyErr_SetString(PyExc_TypeError,
42 "__build_class__: args is not a tuple");
43 return NULL;
44 }
45 nargs = PyTuple_GET_SIZE(args);
46 if (nargs < 2) {
47 PyErr_SetString(PyExc_TypeError,
48 "__build_class__: not enough arguments");
49 return NULL;
50 }
51 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
52 name = PyTuple_GET_ITEM(args, 1);
53 if (!PyUnicode_Check(name)) {
54 PyErr_SetString(PyExc_TypeError,
55 "__build_class__: name is not a string");
56 return NULL;
57 }
58 bases = PyTuple_GetSlice(args, 2, nargs);
59 if (bases == NULL)
60 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 if (kwds == NULL) {
63 meta = NULL;
64 mkw = NULL;
65 }
66 else {
67 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
68 if (mkw == NULL) {
69 Py_DECREF(bases);
70 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000071 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 meta = PyDict_GetItemString(mkw, "metaclass");
73 if (meta != NULL) {
74 Py_INCREF(meta);
75 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
76 Py_DECREF(meta);
77 Py_DECREF(mkw);
78 Py_DECREF(bases);
79 return NULL;
80 }
81 }
82 }
83 if (meta == NULL) {
84 if (PyTuple_GET_SIZE(bases) == 0)
85 meta = (PyObject *) (&PyType_Type);
86 else {
87 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
88 meta = (PyObject *) (base0->ob_type);
89 }
90 Py_INCREF(meta);
91 }
92 prep = PyObject_GetAttrString(meta, "__prepare__");
93 if (prep == NULL) {
94 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
95 PyErr_Clear();
96 ns = PyDict_New();
97 }
98 else {
99 Py_DECREF(meta);
100 Py_XDECREF(mkw);
101 Py_DECREF(bases);
102 return NULL;
103 }
104 }
105 else {
106 PyObject *pargs = PyTuple_Pack(2, name, bases);
107 if (pargs == NULL) {
108 Py_DECREF(prep);
109 Py_DECREF(meta);
110 Py_XDECREF(mkw);
111 Py_DECREF(bases);
112 return NULL;
113 }
114 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
115 Py_DECREF(pargs);
116 Py_DECREF(prep);
117 }
118 if (ns == NULL) {
119 Py_DECREF(meta);
120 Py_XDECREF(mkw);
121 Py_DECREF(bases);
122 return NULL;
123 }
124 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
125 if (cell != NULL) {
126 PyObject *margs;
127 margs = PyTuple_Pack(3, name, bases, ns);
128 if (margs != NULL) {
129 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
130 Py_DECREF(margs);
131 }
132 if (cls != NULL && PyCell_Check(cell)) {
133 Py_INCREF(cls);
134 PyCell_SET(cell, cls);
135 }
136 Py_DECREF(cell);
137 }
138 Py_DECREF(ns);
139 Py_DECREF(meta);
140 Py_XDECREF(mkw);
141 Py_DECREF(bases);
142 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000143}
144
145PyDoc_STRVAR(build_class_doc,
146"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
147\n\
148Internal helper function used by the class statement.");
149
150static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000151builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
154 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400155 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000157
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400158 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 kwlist, &name, &globals, &locals, &fromlist, &level))
160 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400161 return PyImport_ImportModuleLevelObject(name, globals, locals,
162 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000163}
164
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000165PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000166"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000167\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000168Import a module. Because this function is meant for use by the Python\n\
169interpreter and not for general use it is better to use\n\
170importlib.import_module() to programmatically import a module.\n\
171\n\
172The globals argument is only used to determine the context;\n\
173they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000174should be a list of names to emulate ``from name import ...'', or an\n\
175empty list to emulate ``import name''.\n\
176When importing a module from a package, note that __import__('A.B', ...)\n\
177returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000178fromlist is not empty. Level is used to determine whether to perform \n\
179absolute or relative imports. -1 is the original strategy of attempting\n\
180both absolute and relative imports, 0 is absolute, a positive number\n\
181is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000182
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000183
Guido van Rossum79f25d91997-04-29 20:08:16 +0000184static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000185builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000188}
189
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000190PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000191"abs(number) -> number\n\
192\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000193Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000194
Raymond Hettinger96229b12005-03-11 06:49:40 +0000195static PyObject *
196builtin_all(PyObject *self, PyObject *v)
197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 PyObject *it, *item;
199 PyObject *(*iternext)(PyObject *);
200 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 it = PyObject_GetIter(v);
203 if (it == NULL)
204 return NULL;
205 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 for (;;) {
208 item = iternext(it);
209 if (item == NULL)
210 break;
211 cmp = PyObject_IsTrue(item);
212 Py_DECREF(item);
213 if (cmp < 0) {
214 Py_DECREF(it);
215 return NULL;
216 }
217 if (cmp == 0) {
218 Py_DECREF(it);
219 Py_RETURN_FALSE;
220 }
221 }
222 Py_DECREF(it);
223 if (PyErr_Occurred()) {
224 if (PyErr_ExceptionMatches(PyExc_StopIteration))
225 PyErr_Clear();
226 else
227 return NULL;
228 }
229 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000230}
231
232PyDoc_STRVAR(all_doc,
233"all(iterable) -> bool\n\
234\n\
235Return True if bool(x) is True for all values x in the iterable.");
236
237static PyObject *
238builtin_any(PyObject *self, PyObject *v)
239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 PyObject *it, *item;
241 PyObject *(*iternext)(PyObject *);
242 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 it = PyObject_GetIter(v);
245 if (it == NULL)
246 return NULL;
247 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 for (;;) {
250 item = iternext(it);
251 if (item == NULL)
252 break;
253 cmp = PyObject_IsTrue(item);
254 Py_DECREF(item);
255 if (cmp < 0) {
256 Py_DECREF(it);
257 return NULL;
258 }
259 if (cmp == 1) {
260 Py_DECREF(it);
261 Py_RETURN_TRUE;
262 }
263 }
264 Py_DECREF(it);
265 if (PyErr_Occurred()) {
266 if (PyErr_ExceptionMatches(PyExc_StopIteration))
267 PyErr_Clear();
268 else
269 return NULL;
270 }
271 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000272}
273
274PyDoc_STRVAR(any_doc,
275"any(iterable) -> bool\n\
276\n\
277Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000278
Georg Brandl559e5d72008-06-11 18:37:52 +0000279static PyObject *
280builtin_ascii(PyObject *self, PyObject *v)
281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000283}
284
285PyDoc_STRVAR(ascii_doc,
286"ascii(object) -> string\n\
287\n\
288As repr(), return a string containing a printable representation of an\n\
289object, but escape the non-ASCII characters in the string returned by\n\
290repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
291to that returned by repr() in Python 2.");
292
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000293
Guido van Rossum79f25d91997-04-29 20:08:16 +0000294static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000295builtin_bin(PyObject *self, PyObject *v)
296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000298}
299
300PyDoc_STRVAR(bin_doc,
301"bin(number) -> string\n\
302\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -0400303Return the binary representation of an integer.");
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000304
305
Antoine Pitroue71362d2010-11-27 22:00:11 +0000306static PyObject *
307builtin_callable(PyObject *self, PyObject *v)
308{
309 return PyBool_FromLong((long)PyCallable_Check(v));
310}
311
312PyDoc_STRVAR(callable_doc,
313"callable(object) -> bool\n\
314\n\
315Return whether the object is callable (i.e., some kind of function).\n\
316Note that classes are callable, as are instances of classes with a\n\
317__call__() method.");
318
319
Raymond Hettinger17301e92008-03-13 00:19:26 +0000320typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 PyObject_HEAD
322 PyObject *func;
323 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000324} filterobject;
325
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000326static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000327filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 PyObject *func, *seq;
330 PyObject *it;
331 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
334 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
337 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 /* Get iterator. */
340 it = PyObject_GetIter(seq);
341 if (it == NULL)
342 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 /* create filterobject structure */
345 lz = (filterobject *)type->tp_alloc(type, 0);
346 if (lz == NULL) {
347 Py_DECREF(it);
348 return NULL;
349 }
350 Py_INCREF(func);
351 lz->func = func;
352 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000355}
356
357static void
358filter_dealloc(filterobject *lz)
359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 PyObject_GC_UnTrack(lz);
361 Py_XDECREF(lz->func);
362 Py_XDECREF(lz->it);
363 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000364}
365
366static int
367filter_traverse(filterobject *lz, visitproc visit, void *arg)
368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 Py_VISIT(lz->it);
370 Py_VISIT(lz->func);
371 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000372}
373
374static PyObject *
375filter_next(filterobject *lz)
376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 PyObject *item;
378 PyObject *it = lz->it;
379 long ok;
380 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 iternext = *Py_TYPE(it)->tp_iternext;
383 for (;;) {
384 item = iternext(it);
385 if (item == NULL)
386 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
389 ok = PyObject_IsTrue(item);
390 } else {
391 PyObject *good;
392 good = PyObject_CallFunctionObjArgs(lz->func,
393 item, NULL);
394 if (good == NULL) {
395 Py_DECREF(item);
396 return NULL;
397 }
398 ok = PyObject_IsTrue(good);
399 Py_DECREF(good);
400 }
401 if (ok)
402 return item;
403 Py_DECREF(item);
404 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000405}
406
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000407PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000408"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000409\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000410Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000411is true. If function is None, return the items that are true.");
412
413PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 PyVarObject_HEAD_INIT(&PyType_Type, 0)
415 "filter", /* tp_name */
416 sizeof(filterobject), /* tp_basicsize */
417 0, /* tp_itemsize */
418 /* methods */
419 (destructor)filter_dealloc, /* tp_dealloc */
420 0, /* tp_print */
421 0, /* tp_getattr */
422 0, /* tp_setattr */
423 0, /* tp_reserved */
424 0, /* tp_repr */
425 0, /* tp_as_number */
426 0, /* tp_as_sequence */
427 0, /* tp_as_mapping */
428 0, /* tp_hash */
429 0, /* tp_call */
430 0, /* tp_str */
431 PyObject_GenericGetAttr, /* tp_getattro */
432 0, /* tp_setattro */
433 0, /* tp_as_buffer */
434 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
435 Py_TPFLAGS_BASETYPE, /* tp_flags */
436 filter_doc, /* tp_doc */
437 (traverseproc)filter_traverse, /* tp_traverse */
438 0, /* tp_clear */
439 0, /* tp_richcompare */
440 0, /* tp_weaklistoffset */
441 PyObject_SelfIter, /* tp_iter */
442 (iternextfunc)filter_next, /* tp_iternext */
443 0, /* tp_methods */
444 0, /* tp_members */
445 0, /* tp_getset */
446 0, /* tp_base */
447 0, /* tp_dict */
448 0, /* tp_descr_get */
449 0, /* tp_descr_set */
450 0, /* tp_dictoffset */
451 0, /* tp_init */
452 PyType_GenericAlloc, /* tp_alloc */
453 filter_new, /* tp_new */
454 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000455};
456
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000457
Eric Smith8c663262007-08-25 02:26:07 +0000458static PyObject *
459builtin_format(PyObject *self, PyObject *args)
460{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000461 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000462 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000463
Eric Smith8fd3eba2008-02-17 19:48:00 +0000464 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000466
Eric Smith8fd3eba2008-02-17 19:48:00 +0000467 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000468}
469
Eric Smith8c663262007-08-25 02:26:07 +0000470PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000471"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000472\n\
Eric Smith81936692007-08-31 01:14:01 +0000473Returns value.__format__(format_spec)\n\
474format_spec defaults to \"\"");
475
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000476static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000477builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 if (!PyArg_ParseTuple(args, "i:chr", &x))
482 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000485}
486
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000487PyDoc_VAR(chr_doc) = PyDoc_STR(
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000488"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000489\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000490Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000491)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000492#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000493PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000494"\nIf 0x10000 <= i, a surrogate pair is returned."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000495)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000496#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000497;
Guido van Rossum09095f32000-03-10 23:00:52 +0000498
499
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000500static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000501source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 char *str;
504 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 if (PyUnicode_Check(cmd)) {
507 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Victor Stinnerf3fd7332011-03-02 01:03:11 +0000508 cmd = _PyUnicode_AsDefaultEncodedString(cmd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 if (cmd == NULL)
510 return NULL;
511 }
512 else if (!PyObject_CheckReadBuffer(cmd)) {
513 PyErr_Format(PyExc_TypeError,
514 "%s() arg 1 must be a %s object",
515 funcname, what);
516 return NULL;
517 }
518 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
519 return NULL;
520 }
521 if (strlen(str) != size) {
522 PyErr_SetString(PyExc_TypeError,
523 "source code string cannot contain null bytes");
524 return NULL;
525 }
526 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000527}
528
Guido van Rossum79f25d91997-04-29 20:08:16 +0000529static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000530builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 char *str;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000533 PyObject *filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 char *filename;
535 char *startstr;
536 int mode = -1;
537 int dont_inherit = 0;
538 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000539 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 int is_ast;
541 PyCompilerFlags cf;
542 PyObject *cmd;
543 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000544 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000546 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000547
Georg Brandl8334fd92010-12-04 10:26:46 +0000548 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000549 &cmd,
550 PyUnicode_FSConverter, &filename_obj,
551 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000552 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000554
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000555 filename = PyBytes_AS_STRING(filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 if (supplied_flags &
559 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
560 {
561 PyErr_SetString(PyExc_ValueError,
562 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000563 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 }
565 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000566
Georg Brandl8334fd92010-12-04 10:26:46 +0000567 if (optimize < -1 || optimize > 2) {
568 PyErr_SetString(PyExc_ValueError,
569 "compile(): invalid optimize value");
570 goto error;
571 }
572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 if (!dont_inherit) {
574 PyEval_MergeCompilerFlags(&cf);
575 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 if (strcmp(startstr, "exec") == 0)
578 mode = 0;
579 else if (strcmp(startstr, "eval") == 0)
580 mode = 1;
581 else if (strcmp(startstr, "single") == 0)
582 mode = 2;
583 else {
584 PyErr_SetString(PyExc_ValueError,
585 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000586 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 is_ast = PyAST_Check(cmd);
590 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000591 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 if (supplied_flags & PyCF_ONLY_AST) {
594 Py_INCREF(cmd);
595 result = cmd;
596 }
597 else {
598 PyArena *arena;
599 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 arena = PyArena_New();
602 mod = PyAST_obj2mod(cmd, arena, mode);
603 if (mod == NULL) {
604 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000605 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500607 if (!PyAST_Validate(mod)) {
608 PyArena_Free(arena);
609 goto error;
610 }
Georg Brandl8334fd92010-12-04 10:26:46 +0000611 result = (PyObject*)PyAST_CompileEx(mod, filename,
612 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 PyArena_Free(arena);
614 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000615 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
619 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000620 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000621
Georg Brandl8334fd92010-12-04 10:26:46 +0000622 result = Py_CompileStringExFlags(str, filename, start[mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000623 goto finally;
624
625error:
626 result = NULL;
627finally:
628 Py_DECREF(filename_obj);
629 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000630}
631
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000632PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000633"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000634\n\
635Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000636into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000637The filename will be used for run-time error messages.\n\
638The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000639single (interactive) statement, or 'eval' to compile an expression.\n\
640The flags argument, if present, controls which future statements influence\n\
641the compilation of the code.\n\
642The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
643the effects of any future statements in effect in the code calling\n\
644compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000645in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000646
Guido van Rossum79f25d91997-04-29 20:08:16 +0000647static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000648builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
653 return NULL;
654 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000655}
656
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000657PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000658"dir([object]) -> list of strings\n"
659"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000660"If called without an argument, return the names in the current scope.\n"
661"Else, return an alphabetized list of names comprising (some of) the attributes\n"
662"of the given object, and of attributes reachable from it.\n"
663"If the object supplies a method named __dir__, it will be used; otherwise\n"
664"the default dir() logic is used and returns:\n"
665" for a module object: the module's attributes.\n"
666" for a class object: its attributes, and recursively the attributes\n"
667" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000668" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000669" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000670
Guido van Rossum79f25d91997-04-29 20:08:16 +0000671static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000672builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
677 return NULL;
678 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000679}
680
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000681PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000682"divmod(x, y) -> (div, mod)\n\
683\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000684Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000685
686
Guido van Rossum79f25d91997-04-29 20:08:16 +0000687static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000688builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 PyObject *cmd, *result, *tmp = NULL;
691 PyObject *globals = Py_None, *locals = Py_None;
692 char *str;
693 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
696 return NULL;
697 if (locals != Py_None && !PyMapping_Check(locals)) {
698 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
699 return NULL;
700 }
701 if (globals != Py_None && !PyDict_Check(globals)) {
702 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
703 "globals must be a real dict; try eval(expr, {}, mapping)"
704 : "globals must be a dict");
705 return NULL;
706 }
707 if (globals == Py_None) {
708 globals = PyEval_GetGlobals();
709 if (locals == Py_None)
710 locals = PyEval_GetLocals();
711 }
712 else if (locals == Py_None)
713 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 if (globals == NULL || locals == NULL) {
716 PyErr_SetString(PyExc_TypeError,
717 "eval must be given globals and locals "
718 "when called without a frame");
719 return NULL;
720 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
723 if (PyDict_SetItemString(globals, "__builtins__",
724 PyEval_GetBuiltins()) != 0)
725 return NULL;
726 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 if (PyCode_Check(cmd)) {
729 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
730 PyErr_SetString(PyExc_TypeError,
731 "code object passed to eval() may not contain free variables");
732 return NULL;
733 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000734 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
738 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
739 if (str == NULL)
740 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 while (*str == ' ' || *str == '\t')
743 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 (void)PyEval_MergeCompilerFlags(&cf);
746 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
747 Py_XDECREF(tmp);
748 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000749}
750
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000751PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000752"eval(source[, globals[, locals]]) -> value\n\
753\n\
754Evaluate the source in the context of globals and locals.\n\
755The source may be a string representing a Python expression\n\
756or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000757The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000758defaulting to the current globals and locals.\n\
759If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000760
Georg Brandl7cae87c2006-09-06 06:51:57 +0000761static PyObject *
762builtin_exec(PyObject *self, PyObject *args)
763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 PyObject *v;
765 PyObject *prog, *globals = Py_None, *locals = Py_None;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
768 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 if (globals == Py_None) {
771 globals = PyEval_GetGlobals();
772 if (locals == Py_None) {
773 locals = PyEval_GetLocals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 }
775 if (!globals || !locals) {
776 PyErr_SetString(PyExc_SystemError,
777 "globals and locals cannot be NULL");
778 return NULL;
779 }
780 }
781 else if (locals == Py_None)
782 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 if (!PyDict_Check(globals)) {
785 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
786 globals->ob_type->tp_name);
787 return NULL;
788 }
789 if (!PyMapping_Check(locals)) {
790 PyErr_Format(PyExc_TypeError,
791 "arg 3 must be a mapping or None, not %.100s",
792 locals->ob_type->tp_name);
793 return NULL;
794 }
795 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
796 if (PyDict_SetItemString(globals, "__builtins__",
797 PyEval_GetBuiltins()) != 0)
798 return NULL;
799 }
800
801 if (PyCode_Check(prog)) {
802 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
803 PyErr_SetString(PyExc_TypeError,
804 "code object passed to exec() may not "
805 "contain free variables");
806 return NULL;
807 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000808 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 }
810 else {
811 char *str;
812 PyCompilerFlags cf;
813 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
814 str = source_as_string(prog, "exec",
815 "string, bytes or code", &cf);
816 if (str == NULL)
817 return NULL;
818 if (PyEval_MergeCompilerFlags(&cf))
819 v = PyRun_StringFlags(str, Py_file_input, globals,
820 locals, &cf);
821 else
822 v = PyRun_String(str, Py_file_input, globals, locals);
823 }
824 if (v == NULL)
825 return NULL;
826 Py_DECREF(v);
827 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000828}
829
830PyDoc_STRVAR(exec_doc,
831"exec(object[, globals[, locals]])\n\
832\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000833Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000834object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000835The globals and locals are dictionaries, defaulting to the current\n\
836globals and locals. If only globals is given, locals defaults to it.");
837
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000838
Guido van Rossum79f25d91997-04-29 20:08:16 +0000839static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000840builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 PyObject *v, *result, *dflt = NULL;
843 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
846 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 if (!PyUnicode_Check(name)) {
849 PyErr_SetString(PyExc_TypeError,
850 "getattr(): attribute name must be string");
851 return NULL;
852 }
853 result = PyObject_GetAttr(v, name);
854 if (result == NULL && dflt != NULL &&
855 PyErr_ExceptionMatches(PyExc_AttributeError))
856 {
857 PyErr_Clear();
858 Py_INCREF(dflt);
859 result = dflt;
860 }
861 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000862}
863
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000864PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000865"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000866\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000867Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
868When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000869exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000870
871
Guido van Rossum79f25d91997-04-29 20:08:16 +0000872static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000873builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 d = PyEval_GetGlobals();
878 Py_XINCREF(d);
879 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000880}
881
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000882PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000883"globals() -> dictionary\n\
884\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000885Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000886
887
Guido van Rossum79f25d91997-04-29 20:08:16 +0000888static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000889builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 PyObject *v;
892 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
895 return NULL;
896 if (!PyUnicode_Check(name)) {
897 PyErr_SetString(PyExc_TypeError,
898 "hasattr(): attribute name must be string");
899 return NULL;
900 }
901 v = PyObject_GetAttr(v, name);
902 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000903 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000905 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000907 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 }
909 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000910 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000911}
912
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000913PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000914"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000915\n\
916Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000917(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000918
919
Guido van Rossum79f25d91997-04-29 20:08:16 +0000920static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000921builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000924}
925
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000926PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000927"id(object) -> integer\n\
928\n\
929Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000930simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000931
932
Raymond Hettingera6c60372008-03-13 01:26:19 +0000933/* map object ************************************************************/
934
935typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 PyObject_HEAD
937 PyObject *iters;
938 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000939} mapobject;
940
Guido van Rossum79f25d91997-04-29 20:08:16 +0000941static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000942map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 PyObject *it, *iters, *func;
945 mapobject *lz;
946 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
949 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 numargs = PyTuple_Size(args);
952 if (numargs < 2) {
953 PyErr_SetString(PyExc_TypeError,
954 "map() must have at least two arguments.");
955 return NULL;
956 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 iters = PyTuple_New(numargs-1);
959 if (iters == NULL)
960 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 for (i=1 ; i<numargs ; i++) {
963 /* Get iterator. */
964 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
965 if (it == NULL) {
966 Py_DECREF(iters);
967 return NULL;
968 }
969 PyTuple_SET_ITEM(iters, i-1, it);
970 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 /* create mapobject structure */
973 lz = (mapobject *)type->tp_alloc(type, 0);
974 if (lz == NULL) {
975 Py_DECREF(iters);
976 return NULL;
977 }
978 lz->iters = iters;
979 func = PyTuple_GET_ITEM(args, 0);
980 Py_INCREF(func);
981 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000984}
985
986static void
987map_dealloc(mapobject *lz)
988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 PyObject_GC_UnTrack(lz);
990 Py_XDECREF(lz->iters);
991 Py_XDECREF(lz->func);
992 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +0000993}
994
995static int
996map_traverse(mapobject *lz, visitproc visit, void *arg)
997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 Py_VISIT(lz->iters);
999 Py_VISIT(lz->func);
1000 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001001}
1002
1003static PyObject *
1004map_next(mapobject *lz)
1005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 PyObject *val;
1007 PyObject *argtuple;
1008 PyObject *result;
1009 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 numargs = PyTuple_Size(lz->iters);
1012 argtuple = PyTuple_New(numargs);
1013 if (argtuple == NULL)
1014 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 for (i=0 ; i<numargs ; i++) {
1017 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1018 if (val == NULL) {
1019 Py_DECREF(argtuple);
1020 return NULL;
1021 }
1022 PyTuple_SET_ITEM(argtuple, i, val);
1023 }
1024 result = PyObject_Call(lz->func, argtuple, NULL);
1025 Py_DECREF(argtuple);
1026 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001027}
1028
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001029PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001030"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001031\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001032Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001034
Raymond Hettingera6c60372008-03-13 01:26:19 +00001035PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1037 "map", /* tp_name */
1038 sizeof(mapobject), /* tp_basicsize */
1039 0, /* tp_itemsize */
1040 /* methods */
1041 (destructor)map_dealloc, /* tp_dealloc */
1042 0, /* tp_print */
1043 0, /* tp_getattr */
1044 0, /* tp_setattr */
1045 0, /* tp_reserved */
1046 0, /* tp_repr */
1047 0, /* tp_as_number */
1048 0, /* tp_as_sequence */
1049 0, /* tp_as_mapping */
1050 0, /* tp_hash */
1051 0, /* tp_call */
1052 0, /* tp_str */
1053 PyObject_GenericGetAttr, /* tp_getattro */
1054 0, /* tp_setattro */
1055 0, /* tp_as_buffer */
1056 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1057 Py_TPFLAGS_BASETYPE, /* tp_flags */
1058 map_doc, /* tp_doc */
1059 (traverseproc)map_traverse, /* tp_traverse */
1060 0, /* tp_clear */
1061 0, /* tp_richcompare */
1062 0, /* tp_weaklistoffset */
1063 PyObject_SelfIter, /* tp_iter */
1064 (iternextfunc)map_next, /* tp_iternext */
1065 0, /* tp_methods */
1066 0, /* tp_members */
1067 0, /* tp_getset */
1068 0, /* tp_base */
1069 0, /* tp_dict */
1070 0, /* tp_descr_get */
1071 0, /* tp_descr_set */
1072 0, /* tp_dictoffset */
1073 0, /* tp_init */
1074 PyType_GenericAlloc, /* tp_alloc */
1075 map_new, /* tp_new */
1076 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001077};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001078
Guido van Rossum79f25d91997-04-29 20:08:16 +00001079static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001080builtin_next(PyObject *self, PyObject *args)
1081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 PyObject *it, *res;
1083 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1086 return NULL;
1087 if (!PyIter_Check(it)) {
1088 PyErr_Format(PyExc_TypeError,
1089 "%.200s object is not an iterator",
1090 it->ob_type->tp_name);
1091 return NULL;
1092 }
1093
1094 res = (*it->ob_type->tp_iternext)(it);
1095 if (res != NULL) {
1096 return res;
1097 } else if (def != NULL) {
1098 if (PyErr_Occurred()) {
1099 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1100 return NULL;
1101 PyErr_Clear();
1102 }
1103 Py_INCREF(def);
1104 return def;
1105 } else if (PyErr_Occurred()) {
1106 return NULL;
1107 } else {
1108 PyErr_SetNone(PyExc_StopIteration);
1109 return NULL;
1110 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001111}
1112
1113PyDoc_STRVAR(next_doc,
1114"next(iterator[, default])\n\
1115\n\
1116Return the next item from the iterator. If default is given and the iterator\n\
1117is exhausted, it is returned instead of raising StopIteration.");
1118
1119
1120static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001121builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 PyObject *v;
1124 PyObject *name;
1125 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1128 return NULL;
1129 if (PyObject_SetAttr(v, name, value) != 0)
1130 return NULL;
1131 Py_INCREF(Py_None);
1132 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001133}
1134
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001135PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001136"setattr(object, name, value)\n\
1137\n\
1138Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001139``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001140
1141
Guido van Rossum79f25d91997-04-29 20:08:16 +00001142static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001143builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyObject *v;
1146 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1149 return NULL;
1150 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1151 return NULL;
1152 Py_INCREF(Py_None);
1153 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001154}
1155
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001156PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001157"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001158\n\
1159Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001160``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001161
1162
Guido van Rossum79f25d91997-04-29 20:08:16 +00001163static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001164builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001165{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001166 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 x = PyObject_Hash(v);
1169 if (x == -1)
1170 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001171 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001172}
1173
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001174PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001175"hash(object) -> integer\n\
1176\n\
1177Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001178the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001179
1180
Guido van Rossum79f25d91997-04-29 20:08:16 +00001181static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001182builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001185}
1186
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001187PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001188"hex(number) -> string\n\
1189\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001190Return the hexadecimal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001191
1192
Guido van Rossum79f25d91997-04-29 20:08:16 +00001193static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001194builtin_iter(PyObject *self, PyObject *args)
1195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1199 return NULL;
1200 if (w == NULL)
1201 return PyObject_GetIter(v);
1202 if (!PyCallable_Check(v)) {
1203 PyErr_SetString(PyExc_TypeError,
1204 "iter(v, w): v must be callable");
1205 return NULL;
1206 }
1207 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001208}
1209
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001210PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001211"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001212iter(callable, sentinel) -> iterator\n\
1213\n\
1214Get an iterator from an object. In the first form, the argument must\n\
1215supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001216In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001217
1218
1219static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001220builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 res = PyObject_Size(v);
1225 if (res < 0 && PyErr_Occurred())
1226 return NULL;
1227 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001228}
1229
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001230PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001231"len(object) -> integer\n\
1232\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001233Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001234
1235
Guido van Rossum79f25d91997-04-29 20:08:16 +00001236static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001237builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 d = PyEval_GetLocals();
1242 Py_XINCREF(d);
1243 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001244}
1245
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001246PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001247"locals() -> dictionary\n\
1248\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001249Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001250
1251
Guido van Rossum79f25d91997-04-29 20:08:16 +00001252static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001253min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1256 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (PyTuple_Size(args) > 1)
1259 v = args;
1260 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1261 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1264 keyfunc = PyDict_GetItemString(kwds, "key");
1265 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1266 PyErr_Format(PyExc_TypeError,
1267 "%s() got an unexpected keyword argument", name);
1268 return NULL;
1269 }
1270 Py_INCREF(keyfunc);
1271 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 it = PyObject_GetIter(v);
1274 if (it == NULL) {
1275 Py_XDECREF(keyfunc);
1276 return NULL;
1277 }
Tim Petersc3074532001-05-03 07:00:32 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 maxitem = NULL; /* the result */
1280 maxval = NULL; /* the value associated with the result */
1281 while (( item = PyIter_Next(it) )) {
1282 /* get the value from the key function */
1283 if (keyfunc != NULL) {
1284 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1285 if (val == NULL)
1286 goto Fail_it_item;
1287 }
1288 /* no key function; the value is the item */
1289 else {
1290 val = item;
1291 Py_INCREF(val);
1292 }
Tim Petersc3074532001-05-03 07:00:32 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 /* maximum value and item are unset; set them */
1295 if (maxval == NULL) {
1296 maxitem = item;
1297 maxval = val;
1298 }
1299 /* maximum value and item are set; update them as necessary */
1300 else {
1301 int cmp = PyObject_RichCompareBool(val, maxval, op);
1302 if (cmp < 0)
1303 goto Fail_it_item_and_val;
1304 else if (cmp > 0) {
1305 Py_DECREF(maxval);
1306 Py_DECREF(maxitem);
1307 maxval = val;
1308 maxitem = item;
1309 }
1310 else {
1311 Py_DECREF(item);
1312 Py_DECREF(val);
1313 }
1314 }
1315 }
1316 if (PyErr_Occurred())
1317 goto Fail_it;
1318 if (maxval == NULL) {
1319 PyErr_Format(PyExc_ValueError,
1320 "%s() arg is an empty sequence", name);
1321 assert(maxitem == NULL);
1322 }
1323 else
1324 Py_DECREF(maxval);
1325 Py_DECREF(it);
1326 Py_XDECREF(keyfunc);
1327 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001328
1329Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001331Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001333Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 Py_XDECREF(maxval);
1335 Py_XDECREF(maxitem);
1336 Py_DECREF(it);
1337 Py_XDECREF(keyfunc);
1338 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001339}
1340
Guido van Rossum79f25d91997-04-29 20:08:16 +00001341static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001342builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001345}
1346
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001347PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001348"min(iterable[, key=func]) -> value\n\
1349min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001350\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001351With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001352With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001353
1354
Guido van Rossum79f25d91997-04-29 20:08:16 +00001355static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001356builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001359}
1360
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001361PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001362"max(iterable[, key=func]) -> value\n\
1363max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001364\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001365With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001366With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001367
1368
Guido van Rossum79f25d91997-04-29 20:08:16 +00001369static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001370builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001373}
1374
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001375PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001376"oct(number) -> string\n\
1377\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001378Return the octal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001379
1380
Guido van Rossum79f25d91997-04-29 20:08:16 +00001381static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001382builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 long ord;
1385 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 if (PyBytes_Check(obj)) {
1388 size = PyBytes_GET_SIZE(obj);
1389 if (size == 1) {
1390 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1391 return PyLong_FromLong(ord);
1392 }
1393 }
1394 else if (PyUnicode_Check(obj)) {
1395 size = PyUnicode_GET_SIZE(obj);
1396 if (size == 1) {
1397 ord = (long)*PyUnicode_AS_UNICODE(obj);
1398 return PyLong_FromLong(ord);
1399 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001400#ifndef Py_UNICODE_WIDE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 if (size == 2) {
1402 /* Decode a valid surrogate pair */
1403 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1404 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1405 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1406 0xDC00 <= c1 && c1 <= 0xDFFF) {
1407 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1408 0x00010000);
1409 return PyLong_FromLong(ord);
1410 }
1411 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001412#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 }
1414 else if (PyByteArray_Check(obj)) {
1415 /* XXX Hopefully this is temporary */
1416 size = PyByteArray_GET_SIZE(obj);
1417 if (size == 1) {
1418 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1419 return PyLong_FromLong(ord);
1420 }
1421 }
1422 else {
1423 PyErr_Format(PyExc_TypeError,
1424 "ord() expected string of length 1, but " \
1425 "%.200s found", obj->ob_type->tp_name);
1426 return NULL;
1427 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 PyErr_Format(PyExc_TypeError,
1430 "ord() expected a character, "
1431 "but string of length %zd found",
1432 size);
1433 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001434}
1435
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001436PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001437"ord(c) -> integer\n\
1438\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001439Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001440)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001441#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001442PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001443"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001444)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001445#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001446;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001447
1448
Guido van Rossum79f25d91997-04-29 20:08:16 +00001449static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001450builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1455 return NULL;
1456 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001457}
1458
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001459PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001460"pow(x, y[, z]) -> number\n\
1461\n\
1462With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001463equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001464
1465
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001466
Guido van Rossum34343512006-11-30 22:13:52 +00001467static PyObject *
1468builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 static char *kwlist[] = {"sep", "end", "file", 0};
1471 static PyObject *dummy_args;
1472 PyObject *sep = NULL, *end = NULL, *file = NULL;
1473 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 if (dummy_args == NULL) {
1476 if (!(dummy_args = PyTuple_New(0)))
1477 return NULL;
1478 }
1479 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1480 kwlist, &sep, &end, &file))
1481 return NULL;
1482 if (file == NULL || file == Py_None) {
1483 file = PySys_GetObject("stdout");
1484 /* sys.stdout may be None when FILE* stdout isn't connected */
1485 if (file == Py_None)
1486 Py_RETURN_NONE;
1487 }
Guido van Rossum34343512006-11-30 22:13:52 +00001488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 if (sep == Py_None) {
1490 sep = NULL;
1491 }
1492 else if (sep && !PyUnicode_Check(sep)) {
1493 PyErr_Format(PyExc_TypeError,
1494 "sep must be None or a string, not %.200s",
1495 sep->ob_type->tp_name);
1496 return NULL;
1497 }
1498 if (end == Py_None) {
1499 end = NULL;
1500 }
1501 else if (end && !PyUnicode_Check(end)) {
1502 PyErr_Format(PyExc_TypeError,
1503 "end must be None or a string, not %.200s",
1504 end->ob_type->tp_name);
1505 return NULL;
1506 }
Guido van Rossum34343512006-11-30 22:13:52 +00001507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 for (i = 0; i < PyTuple_Size(args); i++) {
1509 if (i > 0) {
1510 if (sep == NULL)
1511 err = PyFile_WriteString(" ", file);
1512 else
1513 err = PyFile_WriteObject(sep, file,
1514 Py_PRINT_RAW);
1515 if (err)
1516 return NULL;
1517 }
1518 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1519 Py_PRINT_RAW);
1520 if (err)
1521 return NULL;
1522 }
Guido van Rossum34343512006-11-30 22:13:52 +00001523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 if (end == NULL)
1525 err = PyFile_WriteString("\n", file);
1526 else
1527 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1528 if (err)
1529 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001532}
1533
1534PyDoc_STRVAR(print_doc,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001535"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001536\n\
1537Prints the values to a stream, or to sys.stdout by default.\n\
1538Optional keyword arguments:\n\
1539file: a file-like object (stream); defaults to the current sys.stdout.\n\
1540sep: string inserted between values, default a space.\n\
1541end: string appended after the last value, default a newline.");
1542
1543
Guido van Rossuma88a0332007-02-26 16:59:55 +00001544static PyObject *
1545builtin_input(PyObject *self, PyObject *args)
1546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 PyObject *promptarg = NULL;
1548 PyObject *fin = PySys_GetObject("stdin");
1549 PyObject *fout = PySys_GetObject("stdout");
1550 PyObject *ferr = PySys_GetObject("stderr");
1551 PyObject *tmp;
1552 long fd;
1553 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 /* Parse arguments */
1556 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1557 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 /* Check that stdin/out/err are intact */
1560 if (fin == NULL || fin == Py_None) {
1561 PyErr_SetString(PyExc_RuntimeError,
1562 "input(): lost sys.stdin");
1563 return NULL;
1564 }
1565 if (fout == NULL || fout == Py_None) {
1566 PyErr_SetString(PyExc_RuntimeError,
1567 "input(): lost sys.stdout");
1568 return NULL;
1569 }
1570 if (ferr == NULL || ferr == Py_None) {
1571 PyErr_SetString(PyExc_RuntimeError,
1572 "input(): lost sys.stderr");
1573 return NULL;
1574 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 /* First of all, flush stderr */
1577 tmp = PyObject_CallMethod(ferr, "flush", "");
1578 if (tmp == NULL)
1579 PyErr_Clear();
1580 else
1581 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 /* We should only use (GNU) readline if Python's sys.stdin and
1584 sys.stdout are the same as C's stdin and stdout, because we
1585 need to pass it those. */
1586 tmp = PyObject_CallMethod(fin, "fileno", "");
1587 if (tmp == NULL) {
1588 PyErr_Clear();
1589 tty = 0;
1590 }
1591 else {
1592 fd = PyLong_AsLong(tmp);
1593 Py_DECREF(tmp);
1594 if (fd < 0 && PyErr_Occurred())
1595 return NULL;
1596 tty = fd == fileno(stdin) && isatty(fd);
1597 }
1598 if (tty) {
1599 tmp = PyObject_CallMethod(fout, "fileno", "");
1600 if (tmp == NULL)
1601 PyErr_Clear();
1602 else {
1603 fd = PyLong_AsLong(tmp);
1604 Py_DECREF(tmp);
1605 if (fd < 0 && PyErr_Occurred())
1606 return NULL;
1607 tty = fd == fileno(stdout) && isatty(fd);
1608 }
1609 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 /* If we're interactive, use (GNU) readline */
1612 if (tty) {
1613 PyObject *po;
1614 char *prompt;
1615 char *s;
1616 PyObject *stdin_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001617 char *stdin_encoding_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001619 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1622 if (!stdin_encoding)
1623 /* stdin is a text stream, so it must have an
1624 encoding. */
1625 return NULL;
Victor Stinner306f0102010-05-19 01:06:22 +00001626 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
1627 if (stdin_encoding_str == NULL) {
1628 Py_DECREF(stdin_encoding);
1629 return NULL;
1630 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 tmp = PyObject_CallMethod(fout, "flush", "");
1632 if (tmp == NULL)
1633 PyErr_Clear();
1634 else
1635 Py_DECREF(tmp);
1636 if (promptarg != NULL) {
1637 PyObject *stringpo;
1638 PyObject *stdout_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001639 char *stdout_encoding_str;
1640 stdout_encoding = PyObject_GetAttrString(fout, "encoding");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 if (stdout_encoding == NULL) {
1642 Py_DECREF(stdin_encoding);
1643 return NULL;
1644 }
Victor Stinner306f0102010-05-19 01:06:22 +00001645 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
1646 if (stdout_encoding_str == NULL) {
1647 Py_DECREF(stdin_encoding);
1648 Py_DECREF(stdout_encoding);
1649 return NULL;
1650 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 stringpo = PyObject_Str(promptarg);
1652 if (stringpo == NULL) {
1653 Py_DECREF(stdin_encoding);
1654 Py_DECREF(stdout_encoding);
1655 return NULL;
1656 }
1657 po = PyUnicode_AsEncodedString(stringpo,
Victor Stinner306f0102010-05-19 01:06:22 +00001658 stdout_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 Py_DECREF(stdout_encoding);
1660 Py_DECREF(stringpo);
1661 if (po == NULL) {
1662 Py_DECREF(stdin_encoding);
1663 return NULL;
1664 }
1665 prompt = PyBytes_AsString(po);
1666 if (prompt == NULL) {
1667 Py_DECREF(stdin_encoding);
1668 Py_DECREF(po);
1669 return NULL;
1670 }
1671 }
1672 else {
1673 po = NULL;
1674 prompt = "";
1675 }
1676 s = PyOS_Readline(stdin, stdout, prompt);
1677 Py_XDECREF(po);
1678 if (s == NULL) {
1679 if (!PyErr_Occurred())
1680 PyErr_SetNone(PyExc_KeyboardInterrupt);
1681 Py_DECREF(stdin_encoding);
1682 return NULL;
1683 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001684
1685 len = strlen(s);
1686 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 PyErr_SetNone(PyExc_EOFError);
1688 result = NULL;
1689 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001690 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 if (len > PY_SSIZE_T_MAX) {
1692 PyErr_SetString(PyExc_OverflowError,
1693 "input: input too long");
1694 result = NULL;
1695 }
1696 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001697 len--; /* strip trailing '\n' */
1698 if (len != 0 && s[len-1] == '\r')
1699 len--; /* strip trailing '\r' */
1700 result = PyUnicode_Decode(s, len, stdin_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 }
1702 }
1703 Py_DECREF(stdin_encoding);
1704 PyMem_FREE(s);
1705 return result;
1706 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 /* Fallback if we're not interactive */
1709 if (promptarg != NULL) {
1710 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1711 return NULL;
1712 }
1713 tmp = PyObject_CallMethod(fout, "flush", "");
1714 if (tmp == NULL)
1715 PyErr_Clear();
1716 else
1717 Py_DECREF(tmp);
1718 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001719}
1720
1721PyDoc_STRVAR(input_doc,
1722"input([prompt]) -> string\n\
1723\n\
1724Read a string from standard input. The trailing newline is stripped.\n\
1725If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1726On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1727is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001728
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001729
Guido van Rossum79f25d91997-04-29 20:08:16 +00001730static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001731builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001734}
1735
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001736PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001737"repr(object) -> string\n\
1738\n\
1739Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001740For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001741
1742
Guido van Rossum79f25d91997-04-29 20:08:16 +00001743static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001744builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 static PyObject *round_str = NULL;
1747 PyObject *ndigits = NULL;
1748 static char *kwlist[] = {"number", "ndigits", 0};
1749 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1752 kwlist, &number, &ndigits))
1753 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 if (Py_TYPE(number)->tp_dict == NULL) {
1756 if (PyType_Ready(Py_TYPE(number)) < 0)
1757 return NULL;
1758 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 if (round_str == NULL) {
1761 round_str = PyUnicode_InternFromString("__round__");
1762 if (round_str == NULL)
1763 return NULL;
1764 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 round = _PyType_Lookup(Py_TYPE(number), round_str);
1767 if (round == NULL) {
1768 PyErr_Format(PyExc_TypeError,
1769 "type %.100s doesn't define __round__ method",
1770 Py_TYPE(number)->tp_name);
1771 return NULL;
1772 }
Alex Martelliae211f92007-08-22 23:21:33 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 if (ndigits == NULL)
1775 return PyObject_CallFunction(round, "O", number);
1776 else
1777 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001778}
1779
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001780PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001781"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001782\n\
1783Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001784This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001785same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001786
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001787
Raymond Hettinger64958a12003-12-17 20:43:33 +00001788static PyObject *
1789builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1792 PyObject *callable;
1793 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1794 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 /* args 1-3 should match listsort in Objects/listobject.c */
1797 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1798 kwlist, &seq, &keyfunc, &reverse))
1799 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 newlist = PySequence_List(seq);
1802 if (newlist == NULL)
1803 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 callable = PyObject_GetAttrString(newlist, "sort");
1806 if (callable == NULL) {
1807 Py_DECREF(newlist);
1808 return NULL;
1809 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 newargs = PyTuple_GetSlice(args, 1, 4);
1812 if (newargs == NULL) {
1813 Py_DECREF(newlist);
1814 Py_DECREF(callable);
1815 return NULL;
1816 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 v = PyObject_Call(callable, newargs, kwds);
1819 Py_DECREF(newargs);
1820 Py_DECREF(callable);
1821 if (v == NULL) {
1822 Py_DECREF(newlist);
1823 return NULL;
1824 }
1825 Py_DECREF(v);
1826 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001827}
1828
1829PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001830"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001831
Guido van Rossum79f25d91997-04-29 20:08:16 +00001832static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001833builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 PyObject *v = NULL;
1836 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1839 return NULL;
1840 if (v == NULL) {
1841 d = PyEval_GetLocals();
1842 if (d == NULL) {
1843 if (!PyErr_Occurred())
1844 PyErr_SetString(PyExc_SystemError,
1845 "vars(): no locals!?");
1846 }
1847 else
1848 Py_INCREF(d);
1849 }
1850 else {
1851 d = PyObject_GetAttrString(v, "__dict__");
1852 if (d == NULL) {
1853 PyErr_SetString(PyExc_TypeError,
1854 "vars() argument must have __dict__ attribute");
1855 return NULL;
1856 }
1857 }
1858 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001859}
1860
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001861PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001862"vars([object]) -> dictionary\n\
1863\n\
1864Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001865With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001866
Alex Martellia70b1912003-04-22 08:12:33 +00001867static PyObject*
1868builtin_sum(PyObject *self, PyObject *args)
1869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 PyObject *seq;
1871 PyObject *result = NULL;
1872 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1875 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 iter = PyObject_GetIter(seq);
1878 if (iter == NULL)
1879 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 if (result == NULL) {
1882 result = PyLong_FromLong(0);
1883 if (result == NULL) {
1884 Py_DECREF(iter);
1885 return NULL;
1886 }
1887 } else {
1888 /* reject string values for 'start' parameter */
1889 if (PyUnicode_Check(result)) {
1890 PyErr_SetString(PyExc_TypeError,
1891 "sum() can't sum strings [use ''.join(seq) instead]");
1892 Py_DECREF(iter);
1893 return NULL;
1894 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001895 if (PyBytes_Check(result)) {
1896 PyErr_SetString(PyExc_TypeError,
1897 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05001898 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001899 return NULL;
1900 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 if (PyByteArray_Check(result)) {
1902 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05001903 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 Py_DECREF(iter);
1905 return NULL;
1906 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 Py_INCREF(result);
1909 }
Alex Martellia70b1912003-04-22 08:12:33 +00001910
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001911#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1913 Assumes all inputs are the same type. If the assumption fails, default
1914 to the more general routine.
1915 */
1916 if (PyLong_CheckExact(result)) {
1917 int overflow;
1918 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1919 /* If this already overflowed, don't even enter the loop. */
1920 if (overflow == 0) {
1921 Py_DECREF(result);
1922 result = NULL;
1923 }
1924 while(result == NULL) {
1925 item = PyIter_Next(iter);
1926 if (item == NULL) {
1927 Py_DECREF(iter);
1928 if (PyErr_Occurred())
1929 return NULL;
1930 return PyLong_FromLong(i_result);
1931 }
1932 if (PyLong_CheckExact(item)) {
1933 long b = PyLong_AsLongAndOverflow(item, &overflow);
1934 long x = i_result + b;
1935 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1936 i_result = x;
1937 Py_DECREF(item);
1938 continue;
1939 }
1940 }
1941 /* Either overflowed or is not an int. Restore real objects and process normally */
1942 result = PyLong_FromLong(i_result);
1943 temp = PyNumber_Add(result, item);
1944 Py_DECREF(result);
1945 Py_DECREF(item);
1946 result = temp;
1947 if (result == NULL) {
1948 Py_DECREF(iter);
1949 return NULL;
1950 }
1951 }
1952 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 if (PyFloat_CheckExact(result)) {
1955 double f_result = PyFloat_AS_DOUBLE(result);
1956 Py_DECREF(result);
1957 result = NULL;
1958 while(result == NULL) {
1959 item = PyIter_Next(iter);
1960 if (item == NULL) {
1961 Py_DECREF(iter);
1962 if (PyErr_Occurred())
1963 return NULL;
1964 return PyFloat_FromDouble(f_result);
1965 }
1966 if (PyFloat_CheckExact(item)) {
1967 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1968 f_result += PyFloat_AS_DOUBLE(item);
1969 PyFPE_END_PROTECT(f_result)
1970 Py_DECREF(item);
1971 continue;
1972 }
1973 if (PyLong_CheckExact(item)) {
1974 long value;
1975 int overflow;
1976 value = PyLong_AsLongAndOverflow(item, &overflow);
1977 if (!overflow) {
1978 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1979 f_result += (double)value;
1980 PyFPE_END_PROTECT(f_result)
1981 Py_DECREF(item);
1982 continue;
1983 }
1984 }
1985 result = PyFloat_FromDouble(f_result);
1986 temp = PyNumber_Add(result, item);
1987 Py_DECREF(result);
1988 Py_DECREF(item);
1989 result = temp;
1990 if (result == NULL) {
1991 Py_DECREF(iter);
1992 return NULL;
1993 }
1994 }
1995 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001996#endif
1997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 for(;;) {
1999 item = PyIter_Next(iter);
2000 if (item == NULL) {
2001 /* error, or end-of-sequence */
2002 if (PyErr_Occurred()) {
2003 Py_DECREF(result);
2004 result = NULL;
2005 }
2006 break;
2007 }
2008 /* It's tempting to use PyNumber_InPlaceAdd instead of
2009 PyNumber_Add here, to avoid quadratic running time
2010 when doing 'sum(list_of_lists, [])'. However, this
2011 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 empty = []
2014 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 would change the value of empty. */
2017 temp = PyNumber_Add(result, item);
2018 Py_DECREF(result);
2019 Py_DECREF(item);
2020 result = temp;
2021 if (result == NULL)
2022 break;
2023 }
2024 Py_DECREF(iter);
2025 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002026}
2027
2028PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002029"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002030\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002031Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2032of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002033empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002034
2035
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002036static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002037builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 PyObject *inst;
2040 PyObject *cls;
2041 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2044 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 retval = PyObject_IsInstance(inst, cls);
2047 if (retval < 0)
2048 return NULL;
2049 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002050}
2051
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002052PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002053"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002054\n\
2055Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002056With a type as second argument, return whether that is the object's type.\n\
2057The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002058isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002059
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002060
2061static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002062builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 PyObject *derived;
2065 PyObject *cls;
2066 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2069 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 retval = PyObject_IsSubclass(derived, cls);
2072 if (retval < 0)
2073 return NULL;
2074 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002075}
2076
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002077PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002078"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002079\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002080Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2081When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2082is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002083
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002084
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002085typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 PyObject_HEAD
2087 Py_ssize_t tuplesize;
2088 PyObject *ittuple; /* tuple of iterators */
2089 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002090} zipobject;
2091
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002092static PyObject *
2093zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 zipobject *lz;
2096 Py_ssize_t i;
2097 PyObject *ittuple; /* tuple of iterators */
2098 PyObject *result;
2099 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2102 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 /* args must be a tuple */
2105 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 /* obtain iterators */
2108 ittuple = PyTuple_New(tuplesize);
2109 if (ittuple == NULL)
2110 return NULL;
2111 for (i=0; i < tuplesize; ++i) {
2112 PyObject *item = PyTuple_GET_ITEM(args, i);
2113 PyObject *it = PyObject_GetIter(item);
2114 if (it == NULL) {
2115 if (PyErr_ExceptionMatches(PyExc_TypeError))
2116 PyErr_Format(PyExc_TypeError,
2117 "zip argument #%zd must support iteration",
2118 i+1);
2119 Py_DECREF(ittuple);
2120 return NULL;
2121 }
2122 PyTuple_SET_ITEM(ittuple, i, it);
2123 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 /* create a result holder */
2126 result = PyTuple_New(tuplesize);
2127 if (result == NULL) {
2128 Py_DECREF(ittuple);
2129 return NULL;
2130 }
2131 for (i=0 ; i < tuplesize ; i++) {
2132 Py_INCREF(Py_None);
2133 PyTuple_SET_ITEM(result, i, Py_None);
2134 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 /* create zipobject structure */
2137 lz = (zipobject *)type->tp_alloc(type, 0);
2138 if (lz == NULL) {
2139 Py_DECREF(ittuple);
2140 Py_DECREF(result);
2141 return NULL;
2142 }
2143 lz->ittuple = ittuple;
2144 lz->tuplesize = tuplesize;
2145 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002148}
2149
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002150static void
2151zip_dealloc(zipobject *lz)
2152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 PyObject_GC_UnTrack(lz);
2154 Py_XDECREF(lz->ittuple);
2155 Py_XDECREF(lz->result);
2156 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002157}
2158
2159static int
2160zip_traverse(zipobject *lz, visitproc visit, void *arg)
2161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 Py_VISIT(lz->ittuple);
2163 Py_VISIT(lz->result);
2164 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002165}
2166
2167static PyObject *
2168zip_next(zipobject *lz)
2169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 Py_ssize_t i;
2171 Py_ssize_t tuplesize = lz->tuplesize;
2172 PyObject *result = lz->result;
2173 PyObject *it;
2174 PyObject *item;
2175 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 if (tuplesize == 0)
2178 return NULL;
2179 if (Py_REFCNT(result) == 1) {
2180 Py_INCREF(result);
2181 for (i=0 ; i < tuplesize ; i++) {
2182 it = PyTuple_GET_ITEM(lz->ittuple, i);
2183 item = (*Py_TYPE(it)->tp_iternext)(it);
2184 if (item == NULL) {
2185 Py_DECREF(result);
2186 return NULL;
2187 }
2188 olditem = PyTuple_GET_ITEM(result, i);
2189 PyTuple_SET_ITEM(result, i, item);
2190 Py_DECREF(olditem);
2191 }
2192 } else {
2193 result = PyTuple_New(tuplesize);
2194 if (result == NULL)
2195 return NULL;
2196 for (i=0 ; i < tuplesize ; i++) {
2197 it = PyTuple_GET_ITEM(lz->ittuple, i);
2198 item = (*Py_TYPE(it)->tp_iternext)(it);
2199 if (item == NULL) {
2200 Py_DECREF(result);
2201 return NULL;
2202 }
2203 PyTuple_SET_ITEM(result, i, item);
2204 }
2205 }
2206 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002207}
Barry Warsawbd599b52000-08-03 15:45:29 +00002208
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002209PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002210"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002211\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002212Return a zip object whose .__next__() method returns a tuple where\n\
2213the i-th element comes from the i-th iterable argument. The .__next__()\n\
2214method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002215is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002216
2217PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2219 "zip", /* tp_name */
2220 sizeof(zipobject), /* tp_basicsize */
2221 0, /* tp_itemsize */
2222 /* methods */
2223 (destructor)zip_dealloc, /* tp_dealloc */
2224 0, /* tp_print */
2225 0, /* tp_getattr */
2226 0, /* tp_setattr */
2227 0, /* tp_reserved */
2228 0, /* tp_repr */
2229 0, /* tp_as_number */
2230 0, /* tp_as_sequence */
2231 0, /* tp_as_mapping */
2232 0, /* tp_hash */
2233 0, /* tp_call */
2234 0, /* tp_str */
2235 PyObject_GenericGetAttr, /* tp_getattro */
2236 0, /* tp_setattro */
2237 0, /* tp_as_buffer */
2238 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2239 Py_TPFLAGS_BASETYPE, /* tp_flags */
2240 zip_doc, /* tp_doc */
2241 (traverseproc)zip_traverse, /* tp_traverse */
2242 0, /* tp_clear */
2243 0, /* tp_richcompare */
2244 0, /* tp_weaklistoffset */
2245 PyObject_SelfIter, /* tp_iter */
2246 (iternextfunc)zip_next, /* tp_iternext */
2247 0, /* tp_methods */
2248 0, /* tp_members */
2249 0, /* tp_getset */
2250 0, /* tp_base */
2251 0, /* tp_dict */
2252 0, /* tp_descr_get */
2253 0, /* tp_descr_set */
2254 0, /* tp_dictoffset */
2255 0, /* tp_init */
2256 PyType_GenericAlloc, /* tp_alloc */
2257 zip_new, /* tp_new */
2258 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002259};
Barry Warsawbd599b52000-08-03 15:45:29 +00002260
2261
Guido van Rossum79f25d91997-04-29 20:08:16 +00002262static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 {"__build_class__", (PyCFunction)builtin___build_class__,
2264 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2265 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2266 {"abs", builtin_abs, METH_O, abs_doc},
2267 {"all", builtin_all, METH_O, all_doc},
2268 {"any", builtin_any, METH_O, any_doc},
2269 {"ascii", builtin_ascii, METH_O, ascii_doc},
2270 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002271 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2273 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2274 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2275 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2276 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2277 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2278 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2279 {"format", builtin_format, METH_VARARGS, format_doc},
2280 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2281 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2282 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2283 {"hash", builtin_hash, METH_O, hash_doc},
2284 {"hex", builtin_hex, METH_O, hex_doc},
2285 {"id", builtin_id, METH_O, id_doc},
2286 {"input", builtin_input, METH_VARARGS, input_doc},
2287 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2288 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2289 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2290 {"len", builtin_len, METH_O, len_doc},
2291 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2292 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2293 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2294 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2295 {"oct", builtin_oct, METH_O, oct_doc},
2296 {"ord", builtin_ord, METH_O, ord_doc},
2297 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2298 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2299 {"repr", builtin_repr, METH_O, repr_doc},
2300 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2301 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2302 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2303 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2304 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2305 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002306};
2307
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002308PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002309"Built-in functions, exceptions, and other objects.\n\
2310\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002311Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002312
Martin v. Löwis1a214512008-06-11 05:26:20 +00002313static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 PyModuleDef_HEAD_INIT,
2315 "builtins",
2316 builtin_doc,
2317 -1, /* multiple "initialization" just copies the module dict. */
2318 builtin_methods,
2319 NULL,
2320 NULL,
2321 NULL,
2322 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002323};
2324
2325
Guido van Rossum25ce5661997-08-02 03:10:38 +00002326PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002327_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 PyObject *mod, *dict, *debug;
2330 mod = PyModule_Create(&builtinsmodule);
2331 if (mod == NULL)
2332 return NULL;
2333 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002334
Tim Peters7571a0f2003-03-23 17:52:28 +00002335#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 /* "builtins" exposes a number of statically allocated objects
2337 * that, before this code was added in 2.3, never showed up in
2338 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2339 * result, programs leaking references to None and False (etc)
2340 * couldn't be diagnosed by examining sys.getobjects(0).
2341 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002342#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2343#else
2344#define ADD_TO_ALL(OBJECT) (void)0
2345#endif
2346
Tim Peters4b7625e2001-09-13 21:37:17 +00002347#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2349 return NULL; \
2350 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 SETBUILTIN("None", Py_None);
2353 SETBUILTIN("Ellipsis", Py_Ellipsis);
2354 SETBUILTIN("NotImplemented", Py_NotImplemented);
2355 SETBUILTIN("False", Py_False);
2356 SETBUILTIN("True", Py_True);
2357 SETBUILTIN("bool", &PyBool_Type);
2358 SETBUILTIN("memoryview", &PyMemoryView_Type);
2359 SETBUILTIN("bytearray", &PyByteArray_Type);
2360 SETBUILTIN("bytes", &PyBytes_Type);
2361 SETBUILTIN("classmethod", &PyClassMethod_Type);
2362 SETBUILTIN("complex", &PyComplex_Type);
2363 SETBUILTIN("dict", &PyDict_Type);
2364 SETBUILTIN("enumerate", &PyEnum_Type);
2365 SETBUILTIN("filter", &PyFilter_Type);
2366 SETBUILTIN("float", &PyFloat_Type);
2367 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2368 SETBUILTIN("property", &PyProperty_Type);
2369 SETBUILTIN("int", &PyLong_Type);
2370 SETBUILTIN("list", &PyList_Type);
2371 SETBUILTIN("map", &PyMap_Type);
2372 SETBUILTIN("object", &PyBaseObject_Type);
2373 SETBUILTIN("range", &PyRange_Type);
2374 SETBUILTIN("reversed", &PyReversed_Type);
2375 SETBUILTIN("set", &PySet_Type);
2376 SETBUILTIN("slice", &PySlice_Type);
2377 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2378 SETBUILTIN("str", &PyUnicode_Type);
2379 SETBUILTIN("super", &PySuper_Type);
2380 SETBUILTIN("tuple", &PyTuple_Type);
2381 SETBUILTIN("type", &PyType_Type);
2382 SETBUILTIN("zip", &PyZip_Type);
2383 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2384 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2385 Py_XDECREF(debug);
2386 return NULL;
2387 }
2388 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002391#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002392#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002393}