blob: 9de8ca036f2465fae8a8ac4f5680ea48d62e361d [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
Benjamin Petersonea281a52011-08-12 23:10:50 -05009#include "asdl.h"
10#include "ast.h"
11
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012#include <ctype.h>
13
Victor Stinnerb744ba12010-05-15 12:27:16 +000014#ifdef HAVE_LANGINFO_H
15#include <langinfo.h> /* CODESET */
16#endif
17
Mark Hammond26cffde42001-05-14 12:17:34 +000018/* The default encoding used by the platform file system APIs
19 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000020
21 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
22 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000023*/
Victor Stinner99b95382011-07-04 14:23:54 +020024#ifdef HAVE_MBCS
Mark Hammond26cffde42001-05-14 12:17:34 +000025const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000027#elif defined(__APPLE__)
28const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerd64e8a72011-07-04 13:48:30 +020030#else
Victor Stinnerb744ba12010-05-15 12:27:16 +000031const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000032int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000033#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000034
Guido van Rossum79f25d91997-04-29 20:08:16 +000035static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000036builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
37{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000038 PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell;
39 PyObject *cls = NULL;
Brett Cannonb94767f2011-02-22 20:15:44 +000040 Py_ssize_t nargs;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 assert(args != NULL);
43 if (!PyTuple_Check(args)) {
44 PyErr_SetString(PyExc_TypeError,
45 "__build_class__: args is not a tuple");
46 return NULL;
47 }
48 nargs = PyTuple_GET_SIZE(args);
49 if (nargs < 2) {
50 PyErr_SetString(PyExc_TypeError,
51 "__build_class__: not enough arguments");
52 return NULL;
53 }
54 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
55 name = PyTuple_GET_ITEM(args, 1);
56 if (!PyUnicode_Check(name)) {
57 PyErr_SetString(PyExc_TypeError,
58 "__build_class__: name is not a string");
59 return NULL;
60 }
61 bases = PyTuple_GetSlice(args, 2, nargs);
62 if (bases == NULL)
63 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 if (kwds == NULL) {
66 meta = NULL;
67 mkw = NULL;
68 }
69 else {
70 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
71 if (mkw == NULL) {
72 Py_DECREF(bases);
73 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000074 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 meta = PyDict_GetItemString(mkw, "metaclass");
76 if (meta != NULL) {
77 Py_INCREF(meta);
78 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
79 Py_DECREF(meta);
80 Py_DECREF(mkw);
81 Py_DECREF(bases);
82 return NULL;
83 }
84 }
85 }
86 if (meta == NULL) {
87 if (PyTuple_GET_SIZE(bases) == 0)
88 meta = (PyObject *) (&PyType_Type);
89 else {
90 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
91 meta = (PyObject *) (base0->ob_type);
92 }
93 Py_INCREF(meta);
94 }
95 prep = PyObject_GetAttrString(meta, "__prepare__");
96 if (prep == NULL) {
97 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
98 PyErr_Clear();
99 ns = PyDict_New();
100 }
101 else {
102 Py_DECREF(meta);
103 Py_XDECREF(mkw);
104 Py_DECREF(bases);
105 return NULL;
106 }
107 }
108 else {
109 PyObject *pargs = PyTuple_Pack(2, name, bases);
110 if (pargs == NULL) {
111 Py_DECREF(prep);
112 Py_DECREF(meta);
113 Py_XDECREF(mkw);
114 Py_DECREF(bases);
115 return NULL;
116 }
117 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
118 Py_DECREF(pargs);
119 Py_DECREF(prep);
120 }
121 if (ns == NULL) {
122 Py_DECREF(meta);
123 Py_XDECREF(mkw);
124 Py_DECREF(bases);
125 return NULL;
126 }
127 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
128 if (cell != NULL) {
129 PyObject *margs;
130 margs = PyTuple_Pack(3, name, bases, ns);
131 if (margs != NULL) {
132 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
133 Py_DECREF(margs);
134 }
135 if (cls != NULL && PyCell_Check(cell)) {
136 Py_INCREF(cls);
137 PyCell_SET(cell, cls);
138 }
139 Py_DECREF(cell);
140 }
141 Py_DECREF(ns);
142 Py_DECREF(meta);
143 Py_XDECREF(mkw);
144 Py_DECREF(bases);
145 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000146}
147
148PyDoc_STRVAR(build_class_doc,
149"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
150\n\
151Internal helper function used by the class statement.");
152
153static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000154builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
157 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400158 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000160
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400161 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 kwlist, &name, &globals, &locals, &fromlist, &level))
163 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400164 return PyImport_ImportModuleLevelObject(name, globals, locals,
165 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000166}
167
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000168PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000169"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000170\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000171Import a module. Because this function is meant for use by the Python\n\
172interpreter and not for general use it is better to use\n\
173importlib.import_module() to programmatically import a module.\n\
174\n\
175The globals argument is only used to determine the context;\n\
176they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000177should be a list of names to emulate ``from name import ...'', or an\n\
178empty list to emulate ``import name''.\n\
179When importing a module from a package, note that __import__('A.B', ...)\n\
180returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000181fromlist is not empty. Level is used to determine whether to perform \n\
182absolute or relative imports. -1 is the original strategy of attempting\n\
183both absolute and relative imports, 0 is absolute, a positive number\n\
184is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000185
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000186
Guido van Rossum79f25d91997-04-29 20:08:16 +0000187static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000188builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000191}
192
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000193PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000194"abs(number) -> number\n\
195\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000196Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000197
Raymond Hettinger96229b12005-03-11 06:49:40 +0000198static PyObject *
199builtin_all(PyObject *self, PyObject *v)
200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 PyObject *it, *item;
202 PyObject *(*iternext)(PyObject *);
203 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 it = PyObject_GetIter(v);
206 if (it == NULL)
207 return NULL;
208 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 for (;;) {
211 item = iternext(it);
212 if (item == NULL)
213 break;
214 cmp = PyObject_IsTrue(item);
215 Py_DECREF(item);
216 if (cmp < 0) {
217 Py_DECREF(it);
218 return NULL;
219 }
220 if (cmp == 0) {
221 Py_DECREF(it);
222 Py_RETURN_FALSE;
223 }
224 }
225 Py_DECREF(it);
226 if (PyErr_Occurred()) {
227 if (PyErr_ExceptionMatches(PyExc_StopIteration))
228 PyErr_Clear();
229 else
230 return NULL;
231 }
232 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000233}
234
235PyDoc_STRVAR(all_doc,
236"all(iterable) -> bool\n\
237\n\
238Return True if bool(x) is True for all values x in the iterable.");
239
240static PyObject *
241builtin_any(PyObject *self, PyObject *v)
242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 PyObject *it, *item;
244 PyObject *(*iternext)(PyObject *);
245 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 it = PyObject_GetIter(v);
248 if (it == NULL)
249 return NULL;
250 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 for (;;) {
253 item = iternext(it);
254 if (item == NULL)
255 break;
256 cmp = PyObject_IsTrue(item);
257 Py_DECREF(item);
258 if (cmp < 0) {
259 Py_DECREF(it);
260 return NULL;
261 }
262 if (cmp == 1) {
263 Py_DECREF(it);
264 Py_RETURN_TRUE;
265 }
266 }
267 Py_DECREF(it);
268 if (PyErr_Occurred()) {
269 if (PyErr_ExceptionMatches(PyExc_StopIteration))
270 PyErr_Clear();
271 else
272 return NULL;
273 }
274 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000275}
276
277PyDoc_STRVAR(any_doc,
278"any(iterable) -> bool\n\
279\n\
280Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000281
Georg Brandl559e5d72008-06-11 18:37:52 +0000282static PyObject *
283builtin_ascii(PyObject *self, PyObject *v)
284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000286}
287
288PyDoc_STRVAR(ascii_doc,
289"ascii(object) -> string\n\
290\n\
291As repr(), return a string containing a printable representation of an\n\
292object, but escape the non-ASCII characters in the string returned by\n\
293repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
294to that returned by repr() in Python 2.");
295
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000296
Guido van Rossum79f25d91997-04-29 20:08:16 +0000297static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000298builtin_bin(PyObject *self, PyObject *v)
299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000301}
302
303PyDoc_STRVAR(bin_doc,
304"bin(number) -> string\n\
305\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -0400306Return the binary representation of an integer.");
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000307
308
Antoine Pitroue71362d2010-11-27 22:00:11 +0000309static PyObject *
310builtin_callable(PyObject *self, PyObject *v)
311{
312 return PyBool_FromLong((long)PyCallable_Check(v));
313}
314
315PyDoc_STRVAR(callable_doc,
316"callable(object) -> bool\n\
317\n\
318Return whether the object is callable (i.e., some kind of function).\n\
319Note that classes are callable, as are instances of classes with a\n\
320__call__() method.");
321
322
Raymond Hettinger17301e92008-03-13 00:19:26 +0000323typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 PyObject_HEAD
325 PyObject *func;
326 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000327} filterobject;
328
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000329static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000330filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 PyObject *func, *seq;
333 PyObject *it;
334 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
337 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
340 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 /* Get iterator. */
343 it = PyObject_GetIter(seq);
344 if (it == NULL)
345 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 /* create filterobject structure */
348 lz = (filterobject *)type->tp_alloc(type, 0);
349 if (lz == NULL) {
350 Py_DECREF(it);
351 return NULL;
352 }
353 Py_INCREF(func);
354 lz->func = func;
355 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000358}
359
360static void
361filter_dealloc(filterobject *lz)
362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 PyObject_GC_UnTrack(lz);
364 Py_XDECREF(lz->func);
365 Py_XDECREF(lz->it);
366 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000367}
368
369static int
370filter_traverse(filterobject *lz, visitproc visit, void *arg)
371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 Py_VISIT(lz->it);
373 Py_VISIT(lz->func);
374 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000375}
376
377static PyObject *
378filter_next(filterobject *lz)
379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 PyObject *item;
381 PyObject *it = lz->it;
382 long ok;
383 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 iternext = *Py_TYPE(it)->tp_iternext;
386 for (;;) {
387 item = iternext(it);
388 if (item == NULL)
389 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
392 ok = PyObject_IsTrue(item);
393 } else {
394 PyObject *good;
395 good = PyObject_CallFunctionObjArgs(lz->func,
396 item, NULL);
397 if (good == NULL) {
398 Py_DECREF(item);
399 return NULL;
400 }
401 ok = PyObject_IsTrue(good);
402 Py_DECREF(good);
403 }
404 if (ok)
405 return item;
406 Py_DECREF(item);
407 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000408}
409
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000410PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000411"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000412\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000413Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000414is true. If function is None, return the items that are true.");
415
416PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 PyVarObject_HEAD_INIT(&PyType_Type, 0)
418 "filter", /* tp_name */
419 sizeof(filterobject), /* tp_basicsize */
420 0, /* tp_itemsize */
421 /* methods */
422 (destructor)filter_dealloc, /* tp_dealloc */
423 0, /* tp_print */
424 0, /* tp_getattr */
425 0, /* tp_setattr */
426 0, /* tp_reserved */
427 0, /* tp_repr */
428 0, /* tp_as_number */
429 0, /* tp_as_sequence */
430 0, /* tp_as_mapping */
431 0, /* tp_hash */
432 0, /* tp_call */
433 0, /* tp_str */
434 PyObject_GenericGetAttr, /* tp_getattro */
435 0, /* tp_setattro */
436 0, /* tp_as_buffer */
437 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
438 Py_TPFLAGS_BASETYPE, /* tp_flags */
439 filter_doc, /* tp_doc */
440 (traverseproc)filter_traverse, /* tp_traverse */
441 0, /* tp_clear */
442 0, /* tp_richcompare */
443 0, /* tp_weaklistoffset */
444 PyObject_SelfIter, /* tp_iter */
445 (iternextfunc)filter_next, /* tp_iternext */
446 0, /* tp_methods */
447 0, /* tp_members */
448 0, /* tp_getset */
449 0, /* tp_base */
450 0, /* tp_dict */
451 0, /* tp_descr_get */
452 0, /* tp_descr_set */
453 0, /* tp_dictoffset */
454 0, /* tp_init */
455 PyType_GenericAlloc, /* tp_alloc */
456 filter_new, /* tp_new */
457 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000458};
459
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000460
Eric Smith8c663262007-08-25 02:26:07 +0000461static PyObject *
462builtin_format(PyObject *self, PyObject *args)
463{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000464 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000465 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000466
Eric Smith8fd3eba2008-02-17 19:48:00 +0000467 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000469
Eric Smith8fd3eba2008-02-17 19:48:00 +0000470 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000471}
472
Eric Smith8c663262007-08-25 02:26:07 +0000473PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000474"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000475\n\
Eric Smith81936692007-08-31 01:14:01 +0000476Returns value.__format__(format_spec)\n\
477format_spec defaults to \"\"");
478
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000479static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000480builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 if (!PyArg_ParseTuple(args, "i:chr", &x))
485 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000488}
489
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000490PyDoc_VAR(chr_doc) = PyDoc_STR(
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000491"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000492\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000493Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000494)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000495#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000496PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000497"\nIf 0x10000 <= i, a surrogate pair is returned."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000498)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000499#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000500;
Guido van Rossum09095f32000-03-10 23:00:52 +0000501
502
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000503static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000504source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 char *str;
507 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 if (PyUnicode_Check(cmd)) {
510 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Victor Stinnerf3fd7332011-03-02 01:03:11 +0000511 cmd = _PyUnicode_AsDefaultEncodedString(cmd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 if (cmd == NULL)
513 return NULL;
514 }
515 else if (!PyObject_CheckReadBuffer(cmd)) {
516 PyErr_Format(PyExc_TypeError,
517 "%s() arg 1 must be a %s object",
518 funcname, what);
519 return NULL;
520 }
521 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
522 return NULL;
523 }
524 if (strlen(str) != size) {
525 PyErr_SetString(PyExc_TypeError,
526 "source code string cannot contain null bytes");
527 return NULL;
528 }
529 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000530}
531
Guido van Rossum79f25d91997-04-29 20:08:16 +0000532static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000533builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 char *str;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000536 PyObject *filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 char *filename;
538 char *startstr;
539 int mode = -1;
540 int dont_inherit = 0;
541 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000542 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 int is_ast;
544 PyCompilerFlags cf;
545 PyObject *cmd;
546 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000547 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000549 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000550
Georg Brandl8334fd92010-12-04 10:26:46 +0000551 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000552 &cmd,
553 PyUnicode_FSConverter, &filename_obj,
554 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000555 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000557
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000558 filename = PyBytes_AS_STRING(filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 if (supplied_flags &
562 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
563 {
564 PyErr_SetString(PyExc_ValueError,
565 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000566 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 }
568 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000569
Georg Brandl8334fd92010-12-04 10:26:46 +0000570 if (optimize < -1 || optimize > 2) {
571 PyErr_SetString(PyExc_ValueError,
572 "compile(): invalid optimize value");
573 goto error;
574 }
575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 if (!dont_inherit) {
577 PyEval_MergeCompilerFlags(&cf);
578 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 if (strcmp(startstr, "exec") == 0)
581 mode = 0;
582 else if (strcmp(startstr, "eval") == 0)
583 mode = 1;
584 else if (strcmp(startstr, "single") == 0)
585 mode = 2;
586 else {
587 PyErr_SetString(PyExc_ValueError,
588 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000589 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 is_ast = PyAST_Check(cmd);
593 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000594 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 if (supplied_flags & PyCF_ONLY_AST) {
597 Py_INCREF(cmd);
598 result = cmd;
599 }
600 else {
601 PyArena *arena;
602 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 arena = PyArena_New();
605 mod = PyAST_obj2mod(cmd, arena, mode);
606 if (mod == NULL) {
607 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000608 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500610 if (!PyAST_Validate(mod)) {
611 PyArena_Free(arena);
612 goto error;
613 }
Georg Brandl8334fd92010-12-04 10:26:46 +0000614 result = (PyObject*)PyAST_CompileEx(mod, filename,
615 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 PyArena_Free(arena);
617 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000618 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
622 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000623 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000624
Georg Brandl8334fd92010-12-04 10:26:46 +0000625 result = Py_CompileStringExFlags(str, filename, start[mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000626 goto finally;
627
628error:
629 result = NULL;
630finally:
631 Py_DECREF(filename_obj);
632 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000633}
634
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000635PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000636"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000637\n\
638Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000639into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000640The filename will be used for run-time error messages.\n\
641The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000642single (interactive) statement, or 'eval' to compile an expression.\n\
643The flags argument, if present, controls which future statements influence\n\
644the compilation of the code.\n\
645The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
646the effects of any future statements in effect in the code calling\n\
647compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000648in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000649
Guido van Rossum79f25d91997-04-29 20:08:16 +0000650static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000651builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
656 return NULL;
657 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000658}
659
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000660PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000661"dir([object]) -> list of strings\n"
662"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000663"If called without an argument, return the names in the current scope.\n"
664"Else, return an alphabetized list of names comprising (some of) the attributes\n"
665"of the given object, and of attributes reachable from it.\n"
666"If the object supplies a method named __dir__, it will be used; otherwise\n"
667"the default dir() logic is used and returns:\n"
668" for a module object: the module's attributes.\n"
669" for a class object: its attributes, and recursively the attributes\n"
670" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000671" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000672" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000673
Guido van Rossum79f25d91997-04-29 20:08:16 +0000674static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000675builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
680 return NULL;
681 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000682}
683
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000684PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000685"divmod(x, y) -> (div, mod)\n\
686\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000687Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000688
689
Guido van Rossum79f25d91997-04-29 20:08:16 +0000690static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000691builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 PyObject *cmd, *result, *tmp = NULL;
694 PyObject *globals = Py_None, *locals = Py_None;
695 char *str;
696 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
699 return NULL;
700 if (locals != Py_None && !PyMapping_Check(locals)) {
701 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
702 return NULL;
703 }
704 if (globals != Py_None && !PyDict_Check(globals)) {
705 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
706 "globals must be a real dict; try eval(expr, {}, mapping)"
707 : "globals must be a dict");
708 return NULL;
709 }
710 if (globals == Py_None) {
711 globals = PyEval_GetGlobals();
712 if (locals == Py_None)
713 locals = PyEval_GetLocals();
714 }
715 else if (locals == Py_None)
716 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 if (globals == NULL || locals == NULL) {
719 PyErr_SetString(PyExc_TypeError,
720 "eval must be given globals and locals "
721 "when called without a frame");
722 return NULL;
723 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
726 if (PyDict_SetItemString(globals, "__builtins__",
727 PyEval_GetBuiltins()) != 0)
728 return NULL;
729 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 if (PyCode_Check(cmd)) {
732 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
733 PyErr_SetString(PyExc_TypeError,
734 "code object passed to eval() may not contain free variables");
735 return NULL;
736 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000737 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
741 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
742 if (str == NULL)
743 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 while (*str == ' ' || *str == '\t')
746 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 (void)PyEval_MergeCompilerFlags(&cf);
749 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
750 Py_XDECREF(tmp);
751 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000752}
753
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000754PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000755"eval(source[, globals[, locals]]) -> value\n\
756\n\
757Evaluate the source in the context of globals and locals.\n\
758The source may be a string representing a Python expression\n\
759or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000760The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000761defaulting to the current globals and locals.\n\
762If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000763
Georg Brandl7cae87c2006-09-06 06:51:57 +0000764static PyObject *
765builtin_exec(PyObject *self, PyObject *args)
766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 PyObject *v;
768 PyObject *prog, *globals = Py_None, *locals = Py_None;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
771 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 if (globals == Py_None) {
774 globals = PyEval_GetGlobals();
775 if (locals == Py_None) {
776 locals = PyEval_GetLocals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 }
778 if (!globals || !locals) {
779 PyErr_SetString(PyExc_SystemError,
780 "globals and locals cannot be NULL");
781 return NULL;
782 }
783 }
784 else if (locals == Py_None)
785 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 if (!PyDict_Check(globals)) {
788 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
789 globals->ob_type->tp_name);
790 return NULL;
791 }
792 if (!PyMapping_Check(locals)) {
793 PyErr_Format(PyExc_TypeError,
794 "arg 3 must be a mapping or None, not %.100s",
795 locals->ob_type->tp_name);
796 return NULL;
797 }
798 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
799 if (PyDict_SetItemString(globals, "__builtins__",
800 PyEval_GetBuiltins()) != 0)
801 return NULL;
802 }
803
804 if (PyCode_Check(prog)) {
805 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
806 PyErr_SetString(PyExc_TypeError,
807 "code object passed to exec() may not "
808 "contain free variables");
809 return NULL;
810 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000811 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 }
813 else {
814 char *str;
815 PyCompilerFlags cf;
816 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
817 str = source_as_string(prog, "exec",
818 "string, bytes or code", &cf);
819 if (str == NULL)
820 return NULL;
821 if (PyEval_MergeCompilerFlags(&cf))
822 v = PyRun_StringFlags(str, Py_file_input, globals,
823 locals, &cf);
824 else
825 v = PyRun_String(str, Py_file_input, globals, locals);
826 }
827 if (v == NULL)
828 return NULL;
829 Py_DECREF(v);
830 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000831}
832
833PyDoc_STRVAR(exec_doc,
834"exec(object[, globals[, locals]])\n\
835\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000836Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000837object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000838The globals and locals are dictionaries, defaulting to the current\n\
839globals and locals. If only globals is given, locals defaults to it.");
840
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000841
Guido van Rossum79f25d91997-04-29 20:08:16 +0000842static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000843builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 PyObject *v, *result, *dflt = NULL;
846 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
849 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 if (!PyUnicode_Check(name)) {
852 PyErr_SetString(PyExc_TypeError,
853 "getattr(): attribute name must be string");
854 return NULL;
855 }
856 result = PyObject_GetAttr(v, name);
857 if (result == NULL && dflt != NULL &&
858 PyErr_ExceptionMatches(PyExc_AttributeError))
859 {
860 PyErr_Clear();
861 Py_INCREF(dflt);
862 result = dflt;
863 }
864 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000865}
866
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000867PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000868"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000869\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000870Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
871When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000872exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000873
874
Guido van Rossum79f25d91997-04-29 20:08:16 +0000875static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000876builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 d = PyEval_GetGlobals();
881 Py_XINCREF(d);
882 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000883}
884
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000885PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000886"globals() -> dictionary\n\
887\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000888Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000889
890
Guido van Rossum79f25d91997-04-29 20:08:16 +0000891static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000892builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 PyObject *v;
895 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
898 return NULL;
899 if (!PyUnicode_Check(name)) {
900 PyErr_SetString(PyExc_TypeError,
901 "hasattr(): attribute name must be string");
902 return NULL;
903 }
904 v = PyObject_GetAttr(v, name);
905 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000906 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000908 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000910 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 }
912 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000913 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000914}
915
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000916PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000917"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000918\n\
919Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000920(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000921
922
Guido van Rossum79f25d91997-04-29 20:08:16 +0000923static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000924builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000927}
928
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000929PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000930"id(object) -> integer\n\
931\n\
932Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000933simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000934
935
Raymond Hettingera6c60372008-03-13 01:26:19 +0000936/* map object ************************************************************/
937
938typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 PyObject_HEAD
940 PyObject *iters;
941 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000942} mapobject;
943
Guido van Rossum79f25d91997-04-29 20:08:16 +0000944static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000945map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 PyObject *it, *iters, *func;
948 mapobject *lz;
949 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
952 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 numargs = PyTuple_Size(args);
955 if (numargs < 2) {
956 PyErr_SetString(PyExc_TypeError,
957 "map() must have at least two arguments.");
958 return NULL;
959 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 iters = PyTuple_New(numargs-1);
962 if (iters == NULL)
963 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 for (i=1 ; i<numargs ; i++) {
966 /* Get iterator. */
967 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
968 if (it == NULL) {
969 Py_DECREF(iters);
970 return NULL;
971 }
972 PyTuple_SET_ITEM(iters, i-1, it);
973 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 /* create mapobject structure */
976 lz = (mapobject *)type->tp_alloc(type, 0);
977 if (lz == NULL) {
978 Py_DECREF(iters);
979 return NULL;
980 }
981 lz->iters = iters;
982 func = PyTuple_GET_ITEM(args, 0);
983 Py_INCREF(func);
984 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000987}
988
989static void
990map_dealloc(mapobject *lz)
991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 PyObject_GC_UnTrack(lz);
993 Py_XDECREF(lz->iters);
994 Py_XDECREF(lz->func);
995 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +0000996}
997
998static int
999map_traverse(mapobject *lz, visitproc visit, void *arg)
1000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 Py_VISIT(lz->iters);
1002 Py_VISIT(lz->func);
1003 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001004}
1005
1006static PyObject *
1007map_next(mapobject *lz)
1008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 PyObject *val;
1010 PyObject *argtuple;
1011 PyObject *result;
1012 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 numargs = PyTuple_Size(lz->iters);
1015 argtuple = PyTuple_New(numargs);
1016 if (argtuple == NULL)
1017 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 for (i=0 ; i<numargs ; i++) {
1020 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1021 if (val == NULL) {
1022 Py_DECREF(argtuple);
1023 return NULL;
1024 }
1025 PyTuple_SET_ITEM(argtuple, i, val);
1026 }
1027 result = PyObject_Call(lz->func, argtuple, NULL);
1028 Py_DECREF(argtuple);
1029 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001030}
1031
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001032PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001033"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001034\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001035Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001037
Raymond Hettingera6c60372008-03-13 01:26:19 +00001038PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1040 "map", /* tp_name */
1041 sizeof(mapobject), /* tp_basicsize */
1042 0, /* tp_itemsize */
1043 /* methods */
1044 (destructor)map_dealloc, /* tp_dealloc */
1045 0, /* tp_print */
1046 0, /* tp_getattr */
1047 0, /* tp_setattr */
1048 0, /* tp_reserved */
1049 0, /* tp_repr */
1050 0, /* tp_as_number */
1051 0, /* tp_as_sequence */
1052 0, /* tp_as_mapping */
1053 0, /* tp_hash */
1054 0, /* tp_call */
1055 0, /* tp_str */
1056 PyObject_GenericGetAttr, /* tp_getattro */
1057 0, /* tp_setattro */
1058 0, /* tp_as_buffer */
1059 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1060 Py_TPFLAGS_BASETYPE, /* tp_flags */
1061 map_doc, /* tp_doc */
1062 (traverseproc)map_traverse, /* tp_traverse */
1063 0, /* tp_clear */
1064 0, /* tp_richcompare */
1065 0, /* tp_weaklistoffset */
1066 PyObject_SelfIter, /* tp_iter */
1067 (iternextfunc)map_next, /* tp_iternext */
1068 0, /* tp_methods */
1069 0, /* tp_members */
1070 0, /* tp_getset */
1071 0, /* tp_base */
1072 0, /* tp_dict */
1073 0, /* tp_descr_get */
1074 0, /* tp_descr_set */
1075 0, /* tp_dictoffset */
1076 0, /* tp_init */
1077 PyType_GenericAlloc, /* tp_alloc */
1078 map_new, /* tp_new */
1079 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001080};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001081
Guido van Rossum79f25d91997-04-29 20:08:16 +00001082static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001083builtin_next(PyObject *self, PyObject *args)
1084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 PyObject *it, *res;
1086 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1089 return NULL;
1090 if (!PyIter_Check(it)) {
1091 PyErr_Format(PyExc_TypeError,
1092 "%.200s object is not an iterator",
1093 it->ob_type->tp_name);
1094 return NULL;
1095 }
1096
1097 res = (*it->ob_type->tp_iternext)(it);
1098 if (res != NULL) {
1099 return res;
1100 } else if (def != NULL) {
1101 if (PyErr_Occurred()) {
1102 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1103 return NULL;
1104 PyErr_Clear();
1105 }
1106 Py_INCREF(def);
1107 return def;
1108 } else if (PyErr_Occurred()) {
1109 return NULL;
1110 } else {
1111 PyErr_SetNone(PyExc_StopIteration);
1112 return NULL;
1113 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001114}
1115
1116PyDoc_STRVAR(next_doc,
1117"next(iterator[, default])\n\
1118\n\
1119Return the next item from the iterator. If default is given and the iterator\n\
1120is exhausted, it is returned instead of raising StopIteration.");
1121
1122
1123static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001124builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 PyObject *v;
1127 PyObject *name;
1128 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1131 return NULL;
1132 if (PyObject_SetAttr(v, name, value) != 0)
1133 return NULL;
1134 Py_INCREF(Py_None);
1135 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001136}
1137
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001138PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001139"setattr(object, name, value)\n\
1140\n\
1141Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001142``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001143
1144
Guido van Rossum79f25d91997-04-29 20:08:16 +00001145static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001146builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 PyObject *v;
1149 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1152 return NULL;
1153 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1154 return NULL;
1155 Py_INCREF(Py_None);
1156 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001157}
1158
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001159PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001160"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001161\n\
1162Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001163``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001164
1165
Guido van Rossum79f25d91997-04-29 20:08:16 +00001166static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001167builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001168{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001169 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 x = PyObject_Hash(v);
1172 if (x == -1)
1173 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001174 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001175}
1176
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001177PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001178"hash(object) -> integer\n\
1179\n\
1180Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001181the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001182
1183
Guido van Rossum79f25d91997-04-29 20:08:16 +00001184static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001185builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001188}
1189
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001190PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001191"hex(number) -> string\n\
1192\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001193Return the hexadecimal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001194
1195
Guido van Rossum79f25d91997-04-29 20:08:16 +00001196static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001197builtin_iter(PyObject *self, PyObject *args)
1198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1202 return NULL;
1203 if (w == NULL)
1204 return PyObject_GetIter(v);
1205 if (!PyCallable_Check(v)) {
1206 PyErr_SetString(PyExc_TypeError,
1207 "iter(v, w): v must be callable");
1208 return NULL;
1209 }
1210 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001211}
1212
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001213PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001214"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001215iter(callable, sentinel) -> iterator\n\
1216\n\
1217Get an iterator from an object. In the first form, the argument must\n\
1218supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001219In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001220
1221
1222static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001223builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 res = PyObject_Size(v);
1228 if (res < 0 && PyErr_Occurred())
1229 return NULL;
1230 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001231}
1232
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001233PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001234"len(object) -> integer\n\
1235\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001236Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001237
1238
Guido van Rossum79f25d91997-04-29 20:08:16 +00001239static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001240builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 d = PyEval_GetLocals();
1245 Py_XINCREF(d);
1246 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001247}
1248
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001249PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001250"locals() -> dictionary\n\
1251\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001252Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001253
1254
Guido van Rossum79f25d91997-04-29 20:08:16 +00001255static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001256min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1259 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 if (PyTuple_Size(args) > 1)
1262 v = args;
1263 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1264 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1267 keyfunc = PyDict_GetItemString(kwds, "key");
1268 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1269 PyErr_Format(PyExc_TypeError,
1270 "%s() got an unexpected keyword argument", name);
1271 return NULL;
1272 }
1273 Py_INCREF(keyfunc);
1274 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 it = PyObject_GetIter(v);
1277 if (it == NULL) {
1278 Py_XDECREF(keyfunc);
1279 return NULL;
1280 }
Tim Petersc3074532001-05-03 07:00:32 +00001281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 maxitem = NULL; /* the result */
1283 maxval = NULL; /* the value associated with the result */
1284 while (( item = PyIter_Next(it) )) {
1285 /* get the value from the key function */
1286 if (keyfunc != NULL) {
1287 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1288 if (val == NULL)
1289 goto Fail_it_item;
1290 }
1291 /* no key function; the value is the item */
1292 else {
1293 val = item;
1294 Py_INCREF(val);
1295 }
Tim Petersc3074532001-05-03 07:00:32 +00001296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 /* maximum value and item are unset; set them */
1298 if (maxval == NULL) {
1299 maxitem = item;
1300 maxval = val;
1301 }
1302 /* maximum value and item are set; update them as necessary */
1303 else {
1304 int cmp = PyObject_RichCompareBool(val, maxval, op);
1305 if (cmp < 0)
1306 goto Fail_it_item_and_val;
1307 else if (cmp > 0) {
1308 Py_DECREF(maxval);
1309 Py_DECREF(maxitem);
1310 maxval = val;
1311 maxitem = item;
1312 }
1313 else {
1314 Py_DECREF(item);
1315 Py_DECREF(val);
1316 }
1317 }
1318 }
1319 if (PyErr_Occurred())
1320 goto Fail_it;
1321 if (maxval == NULL) {
1322 PyErr_Format(PyExc_ValueError,
1323 "%s() arg is an empty sequence", name);
1324 assert(maxitem == NULL);
1325 }
1326 else
1327 Py_DECREF(maxval);
1328 Py_DECREF(it);
1329 Py_XDECREF(keyfunc);
1330 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001331
1332Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001334Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001336Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 Py_XDECREF(maxval);
1338 Py_XDECREF(maxitem);
1339 Py_DECREF(it);
1340 Py_XDECREF(keyfunc);
1341 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001342}
1343
Guido van Rossum79f25d91997-04-29 20:08:16 +00001344static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001345builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001348}
1349
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001350PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001351"min(iterable[, key=func]) -> value\n\
1352min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001353\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001354With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001355With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001356
1357
Guido van Rossum79f25d91997-04-29 20:08:16 +00001358static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001359builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001362}
1363
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001364PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001365"max(iterable[, key=func]) -> value\n\
1366max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001367\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001368With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001369With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001370
1371
Guido van Rossum79f25d91997-04-29 20:08:16 +00001372static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001373builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001376}
1377
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001378PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001379"oct(number) -> string\n\
1380\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001381Return the octal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001382
1383
Guido van Rossum79f25d91997-04-29 20:08:16 +00001384static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001385builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 long ord;
1388 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 if (PyBytes_Check(obj)) {
1391 size = PyBytes_GET_SIZE(obj);
1392 if (size == 1) {
1393 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1394 return PyLong_FromLong(ord);
1395 }
1396 }
1397 else if (PyUnicode_Check(obj)) {
1398 size = PyUnicode_GET_SIZE(obj);
1399 if (size == 1) {
1400 ord = (long)*PyUnicode_AS_UNICODE(obj);
1401 return PyLong_FromLong(ord);
1402 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001403#ifndef Py_UNICODE_WIDE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 if (size == 2) {
1405 /* Decode a valid surrogate pair */
1406 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1407 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1408 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1409 0xDC00 <= c1 && c1 <= 0xDFFF) {
1410 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1411 0x00010000);
1412 return PyLong_FromLong(ord);
1413 }
1414 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001415#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 }
1417 else if (PyByteArray_Check(obj)) {
1418 /* XXX Hopefully this is temporary */
1419 size = PyByteArray_GET_SIZE(obj);
1420 if (size == 1) {
1421 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1422 return PyLong_FromLong(ord);
1423 }
1424 }
1425 else {
1426 PyErr_Format(PyExc_TypeError,
1427 "ord() expected string of length 1, but " \
1428 "%.200s found", obj->ob_type->tp_name);
1429 return NULL;
1430 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 PyErr_Format(PyExc_TypeError,
1433 "ord() expected a character, "
1434 "but string of length %zd found",
1435 size);
1436 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001437}
1438
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001439PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001440"ord(c) -> integer\n\
1441\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001442Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001443)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001444#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001445PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001446"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001447)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001448#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001449;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001450
1451
Guido van Rossum79f25d91997-04-29 20:08:16 +00001452static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001453builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1458 return NULL;
1459 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001460}
1461
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001462PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001463"pow(x, y[, z]) -> number\n\
1464\n\
1465With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001466equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001467
1468
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001469
Guido van Rossum34343512006-11-30 22:13:52 +00001470static PyObject *
1471builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 static char *kwlist[] = {"sep", "end", "file", 0};
1474 static PyObject *dummy_args;
1475 PyObject *sep = NULL, *end = NULL, *file = NULL;
1476 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 if (dummy_args == NULL) {
1479 if (!(dummy_args = PyTuple_New(0)))
1480 return NULL;
1481 }
1482 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1483 kwlist, &sep, &end, &file))
1484 return NULL;
1485 if (file == NULL || file == Py_None) {
1486 file = PySys_GetObject("stdout");
1487 /* sys.stdout may be None when FILE* stdout isn't connected */
1488 if (file == Py_None)
1489 Py_RETURN_NONE;
1490 }
Guido van Rossum34343512006-11-30 22:13:52 +00001491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 if (sep == Py_None) {
1493 sep = NULL;
1494 }
1495 else if (sep && !PyUnicode_Check(sep)) {
1496 PyErr_Format(PyExc_TypeError,
1497 "sep must be None or a string, not %.200s",
1498 sep->ob_type->tp_name);
1499 return NULL;
1500 }
1501 if (end == Py_None) {
1502 end = NULL;
1503 }
1504 else if (end && !PyUnicode_Check(end)) {
1505 PyErr_Format(PyExc_TypeError,
1506 "end must be None or a string, not %.200s",
1507 end->ob_type->tp_name);
1508 return NULL;
1509 }
Guido van Rossum34343512006-11-30 22:13:52 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 for (i = 0; i < PyTuple_Size(args); i++) {
1512 if (i > 0) {
1513 if (sep == NULL)
1514 err = PyFile_WriteString(" ", file);
1515 else
1516 err = PyFile_WriteObject(sep, file,
1517 Py_PRINT_RAW);
1518 if (err)
1519 return NULL;
1520 }
1521 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1522 Py_PRINT_RAW);
1523 if (err)
1524 return NULL;
1525 }
Guido van Rossum34343512006-11-30 22:13:52 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 if (end == NULL)
1528 err = PyFile_WriteString("\n", file);
1529 else
1530 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1531 if (err)
1532 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001535}
1536
1537PyDoc_STRVAR(print_doc,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001538"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001539\n\
1540Prints the values to a stream, or to sys.stdout by default.\n\
1541Optional keyword arguments:\n\
1542file: a file-like object (stream); defaults to the current sys.stdout.\n\
1543sep: string inserted between values, default a space.\n\
1544end: string appended after the last value, default a newline.");
1545
1546
Guido van Rossuma88a0332007-02-26 16:59:55 +00001547static PyObject *
1548builtin_input(PyObject *self, PyObject *args)
1549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 PyObject *promptarg = NULL;
1551 PyObject *fin = PySys_GetObject("stdin");
1552 PyObject *fout = PySys_GetObject("stdout");
1553 PyObject *ferr = PySys_GetObject("stderr");
1554 PyObject *tmp;
1555 long fd;
1556 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 /* Parse arguments */
1559 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1560 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 /* Check that stdin/out/err are intact */
1563 if (fin == NULL || fin == Py_None) {
1564 PyErr_SetString(PyExc_RuntimeError,
1565 "input(): lost sys.stdin");
1566 return NULL;
1567 }
1568 if (fout == NULL || fout == Py_None) {
1569 PyErr_SetString(PyExc_RuntimeError,
1570 "input(): lost sys.stdout");
1571 return NULL;
1572 }
1573 if (ferr == NULL || ferr == Py_None) {
1574 PyErr_SetString(PyExc_RuntimeError,
1575 "input(): lost sys.stderr");
1576 return NULL;
1577 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 /* First of all, flush stderr */
1580 tmp = PyObject_CallMethod(ferr, "flush", "");
1581 if (tmp == NULL)
1582 PyErr_Clear();
1583 else
1584 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 /* We should only use (GNU) readline if Python's sys.stdin and
1587 sys.stdout are the same as C's stdin and stdout, because we
1588 need to pass it those. */
1589 tmp = PyObject_CallMethod(fin, "fileno", "");
1590 if (tmp == NULL) {
1591 PyErr_Clear();
1592 tty = 0;
1593 }
1594 else {
1595 fd = PyLong_AsLong(tmp);
1596 Py_DECREF(tmp);
1597 if (fd < 0 && PyErr_Occurred())
1598 return NULL;
1599 tty = fd == fileno(stdin) && isatty(fd);
1600 }
1601 if (tty) {
1602 tmp = PyObject_CallMethod(fout, "fileno", "");
1603 if (tmp == NULL)
1604 PyErr_Clear();
1605 else {
1606 fd = PyLong_AsLong(tmp);
1607 Py_DECREF(tmp);
1608 if (fd < 0 && PyErr_Occurred())
1609 return NULL;
1610 tty = fd == fileno(stdout) && isatty(fd);
1611 }
1612 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 /* If we're interactive, use (GNU) readline */
1615 if (tty) {
1616 PyObject *po;
1617 char *prompt;
1618 char *s;
1619 PyObject *stdin_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001620 char *stdin_encoding_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001622 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1625 if (!stdin_encoding)
1626 /* stdin is a text stream, so it must have an
1627 encoding. */
1628 return NULL;
Victor Stinner306f0102010-05-19 01:06:22 +00001629 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
1630 if (stdin_encoding_str == NULL) {
1631 Py_DECREF(stdin_encoding);
1632 return NULL;
1633 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 tmp = PyObject_CallMethod(fout, "flush", "");
1635 if (tmp == NULL)
1636 PyErr_Clear();
1637 else
1638 Py_DECREF(tmp);
1639 if (promptarg != NULL) {
1640 PyObject *stringpo;
1641 PyObject *stdout_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001642 char *stdout_encoding_str;
1643 stdout_encoding = PyObject_GetAttrString(fout, "encoding");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 if (stdout_encoding == NULL) {
1645 Py_DECREF(stdin_encoding);
1646 return NULL;
1647 }
Victor Stinner306f0102010-05-19 01:06:22 +00001648 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
1649 if (stdout_encoding_str == NULL) {
1650 Py_DECREF(stdin_encoding);
1651 Py_DECREF(stdout_encoding);
1652 return NULL;
1653 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 stringpo = PyObject_Str(promptarg);
1655 if (stringpo == NULL) {
1656 Py_DECREF(stdin_encoding);
1657 Py_DECREF(stdout_encoding);
1658 return NULL;
1659 }
1660 po = PyUnicode_AsEncodedString(stringpo,
Victor Stinner306f0102010-05-19 01:06:22 +00001661 stdout_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 Py_DECREF(stdout_encoding);
1663 Py_DECREF(stringpo);
1664 if (po == NULL) {
1665 Py_DECREF(stdin_encoding);
1666 return NULL;
1667 }
1668 prompt = PyBytes_AsString(po);
1669 if (prompt == NULL) {
1670 Py_DECREF(stdin_encoding);
1671 Py_DECREF(po);
1672 return NULL;
1673 }
1674 }
1675 else {
1676 po = NULL;
1677 prompt = "";
1678 }
1679 s = PyOS_Readline(stdin, stdout, prompt);
1680 Py_XDECREF(po);
1681 if (s == NULL) {
1682 if (!PyErr_Occurred())
1683 PyErr_SetNone(PyExc_KeyboardInterrupt);
1684 Py_DECREF(stdin_encoding);
1685 return NULL;
1686 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001687
1688 len = strlen(s);
1689 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 PyErr_SetNone(PyExc_EOFError);
1691 result = NULL;
1692 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001693 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 if (len > PY_SSIZE_T_MAX) {
1695 PyErr_SetString(PyExc_OverflowError,
1696 "input: input too long");
1697 result = NULL;
1698 }
1699 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001700 len--; /* strip trailing '\n' */
1701 if (len != 0 && s[len-1] == '\r')
1702 len--; /* strip trailing '\r' */
1703 result = PyUnicode_Decode(s, len, stdin_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 }
1705 }
1706 Py_DECREF(stdin_encoding);
1707 PyMem_FREE(s);
1708 return result;
1709 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 /* Fallback if we're not interactive */
1712 if (promptarg != NULL) {
1713 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1714 return NULL;
1715 }
1716 tmp = PyObject_CallMethod(fout, "flush", "");
1717 if (tmp == NULL)
1718 PyErr_Clear();
1719 else
1720 Py_DECREF(tmp);
1721 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001722}
1723
1724PyDoc_STRVAR(input_doc,
1725"input([prompt]) -> string\n\
1726\n\
1727Read a string from standard input. The trailing newline is stripped.\n\
1728If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1729On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1730is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001731
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001732
Guido van Rossum79f25d91997-04-29 20:08:16 +00001733static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001734builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001737}
1738
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001739PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001740"repr(object) -> string\n\
1741\n\
1742Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001743For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001744
1745
Guido van Rossum79f25d91997-04-29 20:08:16 +00001746static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001747builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 static PyObject *round_str = NULL;
1750 PyObject *ndigits = NULL;
1751 static char *kwlist[] = {"number", "ndigits", 0};
1752 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1755 kwlist, &number, &ndigits))
1756 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 if (Py_TYPE(number)->tp_dict == NULL) {
1759 if (PyType_Ready(Py_TYPE(number)) < 0)
1760 return NULL;
1761 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 if (round_str == NULL) {
1764 round_str = PyUnicode_InternFromString("__round__");
1765 if (round_str == NULL)
1766 return NULL;
1767 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 round = _PyType_Lookup(Py_TYPE(number), round_str);
1770 if (round == NULL) {
1771 PyErr_Format(PyExc_TypeError,
1772 "type %.100s doesn't define __round__ method",
1773 Py_TYPE(number)->tp_name);
1774 return NULL;
1775 }
Alex Martelliae211f92007-08-22 23:21:33 +00001776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 if (ndigits == NULL)
1778 return PyObject_CallFunction(round, "O", number);
1779 else
1780 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001781}
1782
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001783PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001784"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001785\n\
1786Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001787This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001788same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001789
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001790
Raymond Hettinger64958a12003-12-17 20:43:33 +00001791static PyObject *
1792builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1795 PyObject *callable;
1796 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1797 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 /* args 1-3 should match listsort in Objects/listobject.c */
1800 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1801 kwlist, &seq, &keyfunc, &reverse))
1802 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 newlist = PySequence_List(seq);
1805 if (newlist == NULL)
1806 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 callable = PyObject_GetAttrString(newlist, "sort");
1809 if (callable == NULL) {
1810 Py_DECREF(newlist);
1811 return NULL;
1812 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 newargs = PyTuple_GetSlice(args, 1, 4);
1815 if (newargs == NULL) {
1816 Py_DECREF(newlist);
1817 Py_DECREF(callable);
1818 return NULL;
1819 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 v = PyObject_Call(callable, newargs, kwds);
1822 Py_DECREF(newargs);
1823 Py_DECREF(callable);
1824 if (v == NULL) {
1825 Py_DECREF(newlist);
1826 return NULL;
1827 }
1828 Py_DECREF(v);
1829 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001830}
1831
1832PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001833"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001834
Guido van Rossum79f25d91997-04-29 20:08:16 +00001835static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001836builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 PyObject *v = NULL;
1839 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1842 return NULL;
1843 if (v == NULL) {
1844 d = PyEval_GetLocals();
1845 if (d == NULL) {
1846 if (!PyErr_Occurred())
1847 PyErr_SetString(PyExc_SystemError,
1848 "vars(): no locals!?");
1849 }
1850 else
1851 Py_INCREF(d);
1852 }
1853 else {
1854 d = PyObject_GetAttrString(v, "__dict__");
1855 if (d == NULL) {
1856 PyErr_SetString(PyExc_TypeError,
1857 "vars() argument must have __dict__ attribute");
1858 return NULL;
1859 }
1860 }
1861 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001862}
1863
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001864PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001865"vars([object]) -> dictionary\n\
1866\n\
1867Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001868With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001869
Alex Martellia70b1912003-04-22 08:12:33 +00001870static PyObject*
1871builtin_sum(PyObject *self, PyObject *args)
1872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 PyObject *seq;
1874 PyObject *result = NULL;
1875 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1878 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 iter = PyObject_GetIter(seq);
1881 if (iter == NULL)
1882 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 if (result == NULL) {
1885 result = PyLong_FromLong(0);
1886 if (result == NULL) {
1887 Py_DECREF(iter);
1888 return NULL;
1889 }
1890 } else {
1891 /* reject string values for 'start' parameter */
1892 if (PyUnicode_Check(result)) {
1893 PyErr_SetString(PyExc_TypeError,
1894 "sum() can't sum strings [use ''.join(seq) instead]");
1895 Py_DECREF(iter);
1896 return NULL;
1897 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001898 if (PyBytes_Check(result)) {
1899 PyErr_SetString(PyExc_TypeError,
1900 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05001901 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001902 return NULL;
1903 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 if (PyByteArray_Check(result)) {
1905 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05001906 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 Py_DECREF(iter);
1908 return NULL;
1909 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 Py_INCREF(result);
1912 }
Alex Martellia70b1912003-04-22 08:12:33 +00001913
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001914#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1916 Assumes all inputs are the same type. If the assumption fails, default
1917 to the more general routine.
1918 */
1919 if (PyLong_CheckExact(result)) {
1920 int overflow;
1921 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1922 /* If this already overflowed, don't even enter the loop. */
1923 if (overflow == 0) {
1924 Py_DECREF(result);
1925 result = NULL;
1926 }
1927 while(result == NULL) {
1928 item = PyIter_Next(iter);
1929 if (item == NULL) {
1930 Py_DECREF(iter);
1931 if (PyErr_Occurred())
1932 return NULL;
1933 return PyLong_FromLong(i_result);
1934 }
1935 if (PyLong_CheckExact(item)) {
1936 long b = PyLong_AsLongAndOverflow(item, &overflow);
1937 long x = i_result + b;
1938 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1939 i_result = x;
1940 Py_DECREF(item);
1941 continue;
1942 }
1943 }
1944 /* Either overflowed or is not an int. Restore real objects and process normally */
1945 result = PyLong_FromLong(i_result);
1946 temp = PyNumber_Add(result, item);
1947 Py_DECREF(result);
1948 Py_DECREF(item);
1949 result = temp;
1950 if (result == NULL) {
1951 Py_DECREF(iter);
1952 return NULL;
1953 }
1954 }
1955 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 if (PyFloat_CheckExact(result)) {
1958 double f_result = PyFloat_AS_DOUBLE(result);
1959 Py_DECREF(result);
1960 result = NULL;
1961 while(result == NULL) {
1962 item = PyIter_Next(iter);
1963 if (item == NULL) {
1964 Py_DECREF(iter);
1965 if (PyErr_Occurred())
1966 return NULL;
1967 return PyFloat_FromDouble(f_result);
1968 }
1969 if (PyFloat_CheckExact(item)) {
1970 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1971 f_result += PyFloat_AS_DOUBLE(item);
1972 PyFPE_END_PROTECT(f_result)
1973 Py_DECREF(item);
1974 continue;
1975 }
1976 if (PyLong_CheckExact(item)) {
1977 long value;
1978 int overflow;
1979 value = PyLong_AsLongAndOverflow(item, &overflow);
1980 if (!overflow) {
1981 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1982 f_result += (double)value;
1983 PyFPE_END_PROTECT(f_result)
1984 Py_DECREF(item);
1985 continue;
1986 }
1987 }
1988 result = PyFloat_FromDouble(f_result);
1989 temp = PyNumber_Add(result, item);
1990 Py_DECREF(result);
1991 Py_DECREF(item);
1992 result = temp;
1993 if (result == NULL) {
1994 Py_DECREF(iter);
1995 return NULL;
1996 }
1997 }
1998 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001999#endif
2000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 for(;;) {
2002 item = PyIter_Next(iter);
2003 if (item == NULL) {
2004 /* error, or end-of-sequence */
2005 if (PyErr_Occurred()) {
2006 Py_DECREF(result);
2007 result = NULL;
2008 }
2009 break;
2010 }
2011 /* It's tempting to use PyNumber_InPlaceAdd instead of
2012 PyNumber_Add here, to avoid quadratic running time
2013 when doing 'sum(list_of_lists, [])'. However, this
2014 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 empty = []
2017 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 would change the value of empty. */
2020 temp = PyNumber_Add(result, item);
2021 Py_DECREF(result);
2022 Py_DECREF(item);
2023 result = temp;
2024 if (result == NULL)
2025 break;
2026 }
2027 Py_DECREF(iter);
2028 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002029}
2030
2031PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002032"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002033\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002034Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2035of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002036empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002037
2038
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002039static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002040builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 PyObject *inst;
2043 PyObject *cls;
2044 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2047 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 retval = PyObject_IsInstance(inst, cls);
2050 if (retval < 0)
2051 return NULL;
2052 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002053}
2054
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002055PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002056"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002057\n\
2058Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002059With a type as second argument, return whether that is the object's type.\n\
2060The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002061isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002062
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002063
2064static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002065builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 PyObject *derived;
2068 PyObject *cls;
2069 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2072 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 retval = PyObject_IsSubclass(derived, cls);
2075 if (retval < 0)
2076 return NULL;
2077 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002078}
2079
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002080PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002081"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002082\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002083Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2084When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2085is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002086
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002087
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002088typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 PyObject_HEAD
2090 Py_ssize_t tuplesize;
2091 PyObject *ittuple; /* tuple of iterators */
2092 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002093} zipobject;
2094
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002095static PyObject *
2096zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 zipobject *lz;
2099 Py_ssize_t i;
2100 PyObject *ittuple; /* tuple of iterators */
2101 PyObject *result;
2102 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2105 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 /* args must be a tuple */
2108 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 /* obtain iterators */
2111 ittuple = PyTuple_New(tuplesize);
2112 if (ittuple == NULL)
2113 return NULL;
2114 for (i=0; i < tuplesize; ++i) {
2115 PyObject *item = PyTuple_GET_ITEM(args, i);
2116 PyObject *it = PyObject_GetIter(item);
2117 if (it == NULL) {
2118 if (PyErr_ExceptionMatches(PyExc_TypeError))
2119 PyErr_Format(PyExc_TypeError,
2120 "zip argument #%zd must support iteration",
2121 i+1);
2122 Py_DECREF(ittuple);
2123 return NULL;
2124 }
2125 PyTuple_SET_ITEM(ittuple, i, it);
2126 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 /* create a result holder */
2129 result = PyTuple_New(tuplesize);
2130 if (result == NULL) {
2131 Py_DECREF(ittuple);
2132 return NULL;
2133 }
2134 for (i=0 ; i < tuplesize ; i++) {
2135 Py_INCREF(Py_None);
2136 PyTuple_SET_ITEM(result, i, Py_None);
2137 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 /* create zipobject structure */
2140 lz = (zipobject *)type->tp_alloc(type, 0);
2141 if (lz == NULL) {
2142 Py_DECREF(ittuple);
2143 Py_DECREF(result);
2144 return NULL;
2145 }
2146 lz->ittuple = ittuple;
2147 lz->tuplesize = tuplesize;
2148 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002151}
2152
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002153static void
2154zip_dealloc(zipobject *lz)
2155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 PyObject_GC_UnTrack(lz);
2157 Py_XDECREF(lz->ittuple);
2158 Py_XDECREF(lz->result);
2159 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002160}
2161
2162static int
2163zip_traverse(zipobject *lz, visitproc visit, void *arg)
2164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 Py_VISIT(lz->ittuple);
2166 Py_VISIT(lz->result);
2167 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002168}
2169
2170static PyObject *
2171zip_next(zipobject *lz)
2172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 Py_ssize_t i;
2174 Py_ssize_t tuplesize = lz->tuplesize;
2175 PyObject *result = lz->result;
2176 PyObject *it;
2177 PyObject *item;
2178 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 if (tuplesize == 0)
2181 return NULL;
2182 if (Py_REFCNT(result) == 1) {
2183 Py_INCREF(result);
2184 for (i=0 ; i < tuplesize ; i++) {
2185 it = PyTuple_GET_ITEM(lz->ittuple, i);
2186 item = (*Py_TYPE(it)->tp_iternext)(it);
2187 if (item == NULL) {
2188 Py_DECREF(result);
2189 return NULL;
2190 }
2191 olditem = PyTuple_GET_ITEM(result, i);
2192 PyTuple_SET_ITEM(result, i, item);
2193 Py_DECREF(olditem);
2194 }
2195 } else {
2196 result = PyTuple_New(tuplesize);
2197 if (result == NULL)
2198 return NULL;
2199 for (i=0 ; i < tuplesize ; i++) {
2200 it = PyTuple_GET_ITEM(lz->ittuple, i);
2201 item = (*Py_TYPE(it)->tp_iternext)(it);
2202 if (item == NULL) {
2203 Py_DECREF(result);
2204 return NULL;
2205 }
2206 PyTuple_SET_ITEM(result, i, item);
2207 }
2208 }
2209 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002210}
Barry Warsawbd599b52000-08-03 15:45:29 +00002211
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002212PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002213"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002214\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002215Return a zip object whose .__next__() method returns a tuple where\n\
2216the i-th element comes from the i-th iterable argument. The .__next__()\n\
2217method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002218is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002219
2220PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2222 "zip", /* tp_name */
2223 sizeof(zipobject), /* tp_basicsize */
2224 0, /* tp_itemsize */
2225 /* methods */
2226 (destructor)zip_dealloc, /* tp_dealloc */
2227 0, /* tp_print */
2228 0, /* tp_getattr */
2229 0, /* tp_setattr */
2230 0, /* tp_reserved */
2231 0, /* tp_repr */
2232 0, /* tp_as_number */
2233 0, /* tp_as_sequence */
2234 0, /* tp_as_mapping */
2235 0, /* tp_hash */
2236 0, /* tp_call */
2237 0, /* tp_str */
2238 PyObject_GenericGetAttr, /* tp_getattro */
2239 0, /* tp_setattro */
2240 0, /* tp_as_buffer */
2241 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2242 Py_TPFLAGS_BASETYPE, /* tp_flags */
2243 zip_doc, /* tp_doc */
2244 (traverseproc)zip_traverse, /* tp_traverse */
2245 0, /* tp_clear */
2246 0, /* tp_richcompare */
2247 0, /* tp_weaklistoffset */
2248 PyObject_SelfIter, /* tp_iter */
2249 (iternextfunc)zip_next, /* tp_iternext */
2250 0, /* tp_methods */
2251 0, /* tp_members */
2252 0, /* tp_getset */
2253 0, /* tp_base */
2254 0, /* tp_dict */
2255 0, /* tp_descr_get */
2256 0, /* tp_descr_set */
2257 0, /* tp_dictoffset */
2258 0, /* tp_init */
2259 PyType_GenericAlloc, /* tp_alloc */
2260 zip_new, /* tp_new */
2261 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002262};
Barry Warsawbd599b52000-08-03 15:45:29 +00002263
2264
Guido van Rossum79f25d91997-04-29 20:08:16 +00002265static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 {"__build_class__", (PyCFunction)builtin___build_class__,
2267 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2268 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2269 {"abs", builtin_abs, METH_O, abs_doc},
2270 {"all", builtin_all, METH_O, all_doc},
2271 {"any", builtin_any, METH_O, any_doc},
2272 {"ascii", builtin_ascii, METH_O, ascii_doc},
2273 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002274 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2276 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2277 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2278 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2279 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2280 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2281 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2282 {"format", builtin_format, METH_VARARGS, format_doc},
2283 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2284 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2285 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2286 {"hash", builtin_hash, METH_O, hash_doc},
2287 {"hex", builtin_hex, METH_O, hex_doc},
2288 {"id", builtin_id, METH_O, id_doc},
2289 {"input", builtin_input, METH_VARARGS, input_doc},
2290 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2291 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2292 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2293 {"len", builtin_len, METH_O, len_doc},
2294 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2295 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2296 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2297 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2298 {"oct", builtin_oct, METH_O, oct_doc},
2299 {"ord", builtin_ord, METH_O, ord_doc},
2300 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2301 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2302 {"repr", builtin_repr, METH_O, repr_doc},
2303 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2304 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2305 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2306 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2307 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2308 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002309};
2310
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002311PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002312"Built-in functions, exceptions, and other objects.\n\
2313\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002314Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002315
Martin v. Löwis1a214512008-06-11 05:26:20 +00002316static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 PyModuleDef_HEAD_INIT,
2318 "builtins",
2319 builtin_doc,
2320 -1, /* multiple "initialization" just copies the module dict. */
2321 builtin_methods,
2322 NULL,
2323 NULL,
2324 NULL,
2325 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002326};
2327
2328
Guido van Rossum25ce5661997-08-02 03:10:38 +00002329PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002330_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 PyObject *mod, *dict, *debug;
2333 mod = PyModule_Create(&builtinsmodule);
2334 if (mod == NULL)
2335 return NULL;
2336 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002337
Tim Peters7571a0f2003-03-23 17:52:28 +00002338#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 /* "builtins" exposes a number of statically allocated objects
2340 * that, before this code was added in 2.3, never showed up in
2341 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2342 * result, programs leaking references to None and False (etc)
2343 * couldn't be diagnosed by examining sys.getobjects(0).
2344 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002345#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2346#else
2347#define ADD_TO_ALL(OBJECT) (void)0
2348#endif
2349
Tim Peters4b7625e2001-09-13 21:37:17 +00002350#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2352 return NULL; \
2353 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 SETBUILTIN("None", Py_None);
2356 SETBUILTIN("Ellipsis", Py_Ellipsis);
2357 SETBUILTIN("NotImplemented", Py_NotImplemented);
2358 SETBUILTIN("False", Py_False);
2359 SETBUILTIN("True", Py_True);
2360 SETBUILTIN("bool", &PyBool_Type);
2361 SETBUILTIN("memoryview", &PyMemoryView_Type);
2362 SETBUILTIN("bytearray", &PyByteArray_Type);
2363 SETBUILTIN("bytes", &PyBytes_Type);
2364 SETBUILTIN("classmethod", &PyClassMethod_Type);
2365 SETBUILTIN("complex", &PyComplex_Type);
2366 SETBUILTIN("dict", &PyDict_Type);
2367 SETBUILTIN("enumerate", &PyEnum_Type);
2368 SETBUILTIN("filter", &PyFilter_Type);
2369 SETBUILTIN("float", &PyFloat_Type);
2370 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2371 SETBUILTIN("property", &PyProperty_Type);
2372 SETBUILTIN("int", &PyLong_Type);
2373 SETBUILTIN("list", &PyList_Type);
2374 SETBUILTIN("map", &PyMap_Type);
2375 SETBUILTIN("object", &PyBaseObject_Type);
2376 SETBUILTIN("range", &PyRange_Type);
2377 SETBUILTIN("reversed", &PyReversed_Type);
2378 SETBUILTIN("set", &PySet_Type);
2379 SETBUILTIN("slice", &PySlice_Type);
2380 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2381 SETBUILTIN("str", &PyUnicode_Type);
2382 SETBUILTIN("super", &PySuper_Type);
2383 SETBUILTIN("tuple", &PyTuple_Type);
2384 SETBUILTIN("type", &PyType_Type);
2385 SETBUILTIN("zip", &PyZip_Type);
2386 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2387 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2388 Py_XDECREF(debug);
2389 return NULL;
2390 }
2391 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002394#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002395#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002396}