blob: 6258167b6089f1c4eda687c2534f615881cfcc5d [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008
Guido van Rossum6bf62da1997-04-11 20:37:35 +00009#include <ctype.h>
10
Victor Stinnerb744ba12010-05-15 12:27:16 +000011#ifdef HAVE_LANGINFO_H
12#include <langinfo.h> /* CODESET */
13#endif
14
Mark Hammond26cffde42001-05-14 12:17:34 +000015/* The default encoding used by the platform file system APIs
16 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000017
18 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
19 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000020*/
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000021#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Mark Hammond26cffde42001-05-14 12:17:34 +000022const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000023int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000024#elif defined(__APPLE__)
25const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerb744ba12010-05-15 12:27:16 +000027#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
28const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int Py_HasFileSystemDefaultEncoding = 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +000030#else
31const char *Py_FileSystemDefaultEncoding = "utf-8";
32int Py_HasFileSystemDefaultEncoding = 1;
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;
40 Py_ssize_t nargs, nbases;
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;
64 nbases = nargs - 2;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000066 if (kwds == NULL) {
67 meta = NULL;
68 mkw = NULL;
69 }
70 else {
71 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
72 if (mkw == NULL) {
73 Py_DECREF(bases);
74 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000075 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 meta = PyDict_GetItemString(mkw, "metaclass");
77 if (meta != NULL) {
78 Py_INCREF(meta);
79 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
80 Py_DECREF(meta);
81 Py_DECREF(mkw);
82 Py_DECREF(bases);
83 return NULL;
84 }
85 }
86 }
87 if (meta == NULL) {
88 if (PyTuple_GET_SIZE(bases) == 0)
89 meta = (PyObject *) (&PyType_Type);
90 else {
91 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
92 meta = (PyObject *) (base0->ob_type);
93 }
94 Py_INCREF(meta);
95 }
96 prep = PyObject_GetAttrString(meta, "__prepare__");
97 if (prep == NULL) {
98 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
99 PyErr_Clear();
100 ns = PyDict_New();
101 }
102 else {
103 Py_DECREF(meta);
104 Py_XDECREF(mkw);
105 Py_DECREF(bases);
106 return NULL;
107 }
108 }
109 else {
110 PyObject *pargs = PyTuple_Pack(2, name, bases);
111 if (pargs == NULL) {
112 Py_DECREF(prep);
113 Py_DECREF(meta);
114 Py_XDECREF(mkw);
115 Py_DECREF(bases);
116 return NULL;
117 }
118 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
119 Py_DECREF(pargs);
120 Py_DECREF(prep);
121 }
122 if (ns == NULL) {
123 Py_DECREF(meta);
124 Py_XDECREF(mkw);
125 Py_DECREF(bases);
126 return NULL;
127 }
128 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
129 if (cell != NULL) {
130 PyObject *margs;
131 margs = PyTuple_Pack(3, name, bases, ns);
132 if (margs != NULL) {
133 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
134 Py_DECREF(margs);
135 }
136 if (cls != NULL && PyCell_Check(cell)) {
137 Py_INCREF(cls);
138 PyCell_SET(cell, cls);
139 }
140 Py_DECREF(cell);
141 }
142 Py_DECREF(ns);
143 Py_DECREF(meta);
144 Py_XDECREF(mkw);
145 Py_DECREF(bases);
146 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000147}
148
149PyDoc_STRVAR(build_class_doc,
150"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
151\n\
152Internal helper function used by the class statement.");
153
154static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000155builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
158 "level", 0};
159 char *name;
160 PyObject *globals = NULL;
161 PyObject *locals = NULL;
162 PyObject *fromlist = NULL;
163 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
166 kwlist, &name, &globals, &locals, &fromlist, &level))
167 return NULL;
168 return PyImport_ImportModuleLevel(name, globals, locals,
169 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000170}
171
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000172PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000173"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000174\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000175Import a module. Because this function is meant for use by the Python\n\
176interpreter and not for general use it is better to use\n\
177importlib.import_module() to programmatically import a module.\n\
178\n\
179The globals argument is only used to determine the context;\n\
180they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000181should be a list of names to emulate ``from name import ...'', or an\n\
182empty list to emulate ``import name''.\n\
183When importing a module from a package, note that __import__('A.B', ...)\n\
184returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000185fromlist is not empty. Level is used to determine whether to perform \n\
186absolute or relative imports. -1 is the original strategy of attempting\n\
187both absolute and relative imports, 0 is absolute, a positive number\n\
188is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000189
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000190
Guido van Rossum79f25d91997-04-29 20:08:16 +0000191static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000192builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000195}
196
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000197PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000198"abs(number) -> number\n\
199\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000200Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000201
Raymond Hettinger96229b12005-03-11 06:49:40 +0000202static PyObject *
203builtin_all(PyObject *self, PyObject *v)
204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 PyObject *it, *item;
206 PyObject *(*iternext)(PyObject *);
207 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 it = PyObject_GetIter(v);
210 if (it == NULL)
211 return NULL;
212 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 for (;;) {
215 item = iternext(it);
216 if (item == NULL)
217 break;
218 cmp = PyObject_IsTrue(item);
219 Py_DECREF(item);
220 if (cmp < 0) {
221 Py_DECREF(it);
222 return NULL;
223 }
224 if (cmp == 0) {
225 Py_DECREF(it);
226 Py_RETURN_FALSE;
227 }
228 }
229 Py_DECREF(it);
230 if (PyErr_Occurred()) {
231 if (PyErr_ExceptionMatches(PyExc_StopIteration))
232 PyErr_Clear();
233 else
234 return NULL;
235 }
236 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000237}
238
239PyDoc_STRVAR(all_doc,
240"all(iterable) -> bool\n\
241\n\
242Return True if bool(x) is True for all values x in the iterable.");
243
244static PyObject *
245builtin_any(PyObject *self, PyObject *v)
246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 PyObject *it, *item;
248 PyObject *(*iternext)(PyObject *);
249 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 it = PyObject_GetIter(v);
252 if (it == NULL)
253 return NULL;
254 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 for (;;) {
257 item = iternext(it);
258 if (item == NULL)
259 break;
260 cmp = PyObject_IsTrue(item);
261 Py_DECREF(item);
262 if (cmp < 0) {
263 Py_DECREF(it);
264 return NULL;
265 }
266 if (cmp == 1) {
267 Py_DECREF(it);
268 Py_RETURN_TRUE;
269 }
270 }
271 Py_DECREF(it);
272 if (PyErr_Occurred()) {
273 if (PyErr_ExceptionMatches(PyExc_StopIteration))
274 PyErr_Clear();
275 else
276 return NULL;
277 }
278 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000279}
280
281PyDoc_STRVAR(any_doc,
282"any(iterable) -> bool\n\
283\n\
284Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000285
Georg Brandl559e5d72008-06-11 18:37:52 +0000286static PyObject *
287builtin_ascii(PyObject *self, PyObject *v)
288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000290}
291
292PyDoc_STRVAR(ascii_doc,
293"ascii(object) -> string\n\
294\n\
295As repr(), return a string containing a printable representation of an\n\
296object, but escape the non-ASCII characters in the string returned by\n\
297repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
298to that returned by repr() in Python 2.");
299
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000300
Guido van Rossum79f25d91997-04-29 20:08:16 +0000301static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000302builtin_bin(PyObject *self, PyObject *v)
303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000305}
306
307PyDoc_STRVAR(bin_doc,
308"bin(number) -> string\n\
309\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -0400310Return the binary representation of an integer.");
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000311
312
Antoine Pitroue71362d2010-11-27 22:00:11 +0000313static PyObject *
314builtin_callable(PyObject *self, PyObject *v)
315{
316 return PyBool_FromLong((long)PyCallable_Check(v));
317}
318
319PyDoc_STRVAR(callable_doc,
320"callable(object) -> bool\n\
321\n\
322Return whether the object is callable (i.e., some kind of function).\n\
323Note that classes are callable, as are instances of classes with a\n\
324__call__() method.");
325
326
Raymond Hettinger17301e92008-03-13 00:19:26 +0000327typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 PyObject_HEAD
329 PyObject *func;
330 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000331} filterobject;
332
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000333static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000334filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 PyObject *func, *seq;
337 PyObject *it;
338 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
341 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
344 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 /* Get iterator. */
347 it = PyObject_GetIter(seq);
348 if (it == NULL)
349 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 /* create filterobject structure */
352 lz = (filterobject *)type->tp_alloc(type, 0);
353 if (lz == NULL) {
354 Py_DECREF(it);
355 return NULL;
356 }
357 Py_INCREF(func);
358 lz->func = func;
359 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000362}
363
364static void
365filter_dealloc(filterobject *lz)
366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 PyObject_GC_UnTrack(lz);
368 Py_XDECREF(lz->func);
369 Py_XDECREF(lz->it);
370 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000371}
372
373static int
374filter_traverse(filterobject *lz, visitproc visit, void *arg)
375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 Py_VISIT(lz->it);
377 Py_VISIT(lz->func);
378 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000379}
380
381static PyObject *
382filter_next(filterobject *lz)
383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 PyObject *item;
385 PyObject *it = lz->it;
386 long ok;
387 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 iternext = *Py_TYPE(it)->tp_iternext;
390 for (;;) {
391 item = iternext(it);
392 if (item == NULL)
393 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
396 ok = PyObject_IsTrue(item);
397 } else {
398 PyObject *good;
399 good = PyObject_CallFunctionObjArgs(lz->func,
400 item, NULL);
401 if (good == NULL) {
402 Py_DECREF(item);
403 return NULL;
404 }
405 ok = PyObject_IsTrue(good);
406 Py_DECREF(good);
407 }
408 if (ok)
409 return item;
410 Py_DECREF(item);
411 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000412}
413
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000414PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000415"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000416\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000417Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000418is true. If function is None, return the items that are true.");
419
420PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 PyVarObject_HEAD_INIT(&PyType_Type, 0)
422 "filter", /* tp_name */
423 sizeof(filterobject), /* tp_basicsize */
424 0, /* tp_itemsize */
425 /* methods */
426 (destructor)filter_dealloc, /* tp_dealloc */
427 0, /* tp_print */
428 0, /* tp_getattr */
429 0, /* tp_setattr */
430 0, /* tp_reserved */
431 0, /* tp_repr */
432 0, /* tp_as_number */
433 0, /* tp_as_sequence */
434 0, /* tp_as_mapping */
435 0, /* tp_hash */
436 0, /* tp_call */
437 0, /* tp_str */
438 PyObject_GenericGetAttr, /* tp_getattro */
439 0, /* tp_setattro */
440 0, /* tp_as_buffer */
441 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
442 Py_TPFLAGS_BASETYPE, /* tp_flags */
443 filter_doc, /* tp_doc */
444 (traverseproc)filter_traverse, /* tp_traverse */
445 0, /* tp_clear */
446 0, /* tp_richcompare */
447 0, /* tp_weaklistoffset */
448 PyObject_SelfIter, /* tp_iter */
449 (iternextfunc)filter_next, /* tp_iternext */
450 0, /* tp_methods */
451 0, /* tp_members */
452 0, /* tp_getset */
453 0, /* tp_base */
454 0, /* tp_dict */
455 0, /* tp_descr_get */
456 0, /* tp_descr_set */
457 0, /* tp_dictoffset */
458 0, /* tp_init */
459 PyType_GenericAlloc, /* tp_alloc */
460 filter_new, /* tp_new */
461 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000462};
463
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000464
Eric Smith8c663262007-08-25 02:26:07 +0000465static PyObject *
466builtin_format(PyObject *self, PyObject *args)
467{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000468 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000469 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000470
Eric Smith8fd3eba2008-02-17 19:48:00 +0000471 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000473
Eric Smith8fd3eba2008-02-17 19:48:00 +0000474 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000475}
476
Eric Smith8c663262007-08-25 02:26:07 +0000477PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000478"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000479\n\
Eric Smith81936692007-08-31 01:14:01 +0000480Returns value.__format__(format_spec)\n\
481format_spec defaults to \"\"");
482
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000483static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000484builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 if (!PyArg_ParseTuple(args, "i:chr", &x))
489 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000492}
493
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000494PyDoc_VAR(chr_doc) = PyDoc_STR(
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000495"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000496\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000497Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000498)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000499#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000500PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000501"\nIf 0x10000 <= i, a surrogate pair is returned."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000502)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000503#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000504;
Guido van Rossum09095f32000-03-10 23:00:52 +0000505
506
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000507static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000508source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 char *str;
511 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 if (PyUnicode_Check(cmd)) {
514 cf->cf_flags |= PyCF_IGNORE_COOKIE;
515 cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL);
516 if (cmd == NULL)
517 return NULL;
518 }
519 else if (!PyObject_CheckReadBuffer(cmd)) {
520 PyErr_Format(PyExc_TypeError,
521 "%s() arg 1 must be a %s object",
522 funcname, what);
523 return NULL;
524 }
525 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
526 return NULL;
527 }
528 if (strlen(str) != size) {
529 PyErr_SetString(PyExc_TypeError,
530 "source code string cannot contain null bytes");
531 return NULL;
532 }
533 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000534}
535
Guido van Rossum79f25d91997-04-29 20:08:16 +0000536static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000537builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 char *str;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000540 PyObject *filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 char *filename;
542 char *startstr;
543 int mode = -1;
544 int dont_inherit = 0;
545 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000546 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 int is_ast;
548 PyCompilerFlags cf;
549 PyObject *cmd;
550 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000551 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000553 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000554
Georg Brandl8334fd92010-12-04 10:26:46 +0000555 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000556 &cmd,
557 PyUnicode_FSConverter, &filename_obj,
558 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000559 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000561
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000562 filename = PyBytes_AS_STRING(filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 if (supplied_flags &
566 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
567 {
568 PyErr_SetString(PyExc_ValueError,
569 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000570 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 }
572 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000573
Georg Brandl8334fd92010-12-04 10:26:46 +0000574 if (optimize < -1 || optimize > 2) {
575 PyErr_SetString(PyExc_ValueError,
576 "compile(): invalid optimize value");
577 goto error;
578 }
579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 if (!dont_inherit) {
581 PyEval_MergeCompilerFlags(&cf);
582 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 if (strcmp(startstr, "exec") == 0)
585 mode = 0;
586 else if (strcmp(startstr, "eval") == 0)
587 mode = 1;
588 else if (strcmp(startstr, "single") == 0)
589 mode = 2;
590 else {
591 PyErr_SetString(PyExc_ValueError,
592 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000593 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 is_ast = PyAST_Check(cmd);
597 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000598 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 if (supplied_flags & PyCF_ONLY_AST) {
601 Py_INCREF(cmd);
602 result = cmd;
603 }
604 else {
605 PyArena *arena;
606 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 arena = PyArena_New();
609 mod = PyAST_obj2mod(cmd, arena, mode);
610 if (mod == NULL) {
611 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000612 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 }
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;
769 int plain = 0;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
772 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 if (globals == Py_None) {
775 globals = PyEval_GetGlobals();
776 if (locals == Py_None) {
777 locals = PyEval_GetLocals();
778 plain = 1;
779 }
780 if (!globals || !locals) {
781 PyErr_SetString(PyExc_SystemError,
782 "globals and locals cannot be NULL");
783 return NULL;
784 }
785 }
786 else if (locals == Py_None)
787 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 if (!PyDict_Check(globals)) {
790 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
791 globals->ob_type->tp_name);
792 return NULL;
793 }
794 if (!PyMapping_Check(locals)) {
795 PyErr_Format(PyExc_TypeError,
796 "arg 3 must be a mapping or None, not %.100s",
797 locals->ob_type->tp_name);
798 return NULL;
799 }
800 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
801 if (PyDict_SetItemString(globals, "__builtins__",
802 PyEval_GetBuiltins()) != 0)
803 return NULL;
804 }
805
806 if (PyCode_Check(prog)) {
807 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
808 PyErr_SetString(PyExc_TypeError,
809 "code object passed to exec() may not "
810 "contain free variables");
811 return NULL;
812 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000813 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 }
815 else {
816 char *str;
817 PyCompilerFlags cf;
818 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
819 str = source_as_string(prog, "exec",
820 "string, bytes or code", &cf);
821 if (str == NULL)
822 return NULL;
823 if (PyEval_MergeCompilerFlags(&cf))
824 v = PyRun_StringFlags(str, Py_file_input, globals,
825 locals, &cf);
826 else
827 v = PyRun_String(str, Py_file_input, globals, locals);
828 }
829 if (v == NULL)
830 return NULL;
831 Py_DECREF(v);
832 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000833}
834
835PyDoc_STRVAR(exec_doc,
836"exec(object[, globals[, locals]])\n\
837\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000838Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000839object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000840The globals and locals are dictionaries, defaulting to the current\n\
841globals and locals. If only globals is given, locals defaults to it.");
842
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000843
Guido van Rossum79f25d91997-04-29 20:08:16 +0000844static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000845builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 PyObject *v, *result, *dflt = NULL;
848 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
851 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 if (!PyUnicode_Check(name)) {
854 PyErr_SetString(PyExc_TypeError,
855 "getattr(): attribute name must be string");
856 return NULL;
857 }
858 result = PyObject_GetAttr(v, name);
859 if (result == NULL && dflt != NULL &&
860 PyErr_ExceptionMatches(PyExc_AttributeError))
861 {
862 PyErr_Clear();
863 Py_INCREF(dflt);
864 result = dflt;
865 }
866 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000867}
868
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000869PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000870"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000871\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000872Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
873When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000874exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000875
876
Guido van Rossum79f25d91997-04-29 20:08:16 +0000877static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000878builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 d = PyEval_GetGlobals();
883 Py_XINCREF(d);
884 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000885}
886
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000887PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000888"globals() -> dictionary\n\
889\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000890Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000891
892
Guido van Rossum79f25d91997-04-29 20:08:16 +0000893static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000894builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 PyObject *v;
897 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
900 return NULL;
901 if (!PyUnicode_Check(name)) {
902 PyErr_SetString(PyExc_TypeError,
903 "hasattr(): attribute name must be string");
904 return NULL;
905 }
906 v = PyObject_GetAttr(v, name);
907 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000908 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000910 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000912 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 }
914 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000915 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000916}
917
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000918PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000919"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000920\n\
921Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000922(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000923
924
Guido van Rossum79f25d91997-04-29 20:08:16 +0000925static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000926builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000929}
930
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000931PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000932"id(object) -> integer\n\
933\n\
934Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000935simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000936
937
Raymond Hettingera6c60372008-03-13 01:26:19 +0000938/* map object ************************************************************/
939
940typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 PyObject_HEAD
942 PyObject *iters;
943 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000944} mapobject;
945
Guido van Rossum79f25d91997-04-29 20:08:16 +0000946static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000947map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 PyObject *it, *iters, *func;
950 mapobject *lz;
951 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
954 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 numargs = PyTuple_Size(args);
957 if (numargs < 2) {
958 PyErr_SetString(PyExc_TypeError,
959 "map() must have at least two arguments.");
960 return NULL;
961 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 iters = PyTuple_New(numargs-1);
964 if (iters == NULL)
965 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 for (i=1 ; i<numargs ; i++) {
968 /* Get iterator. */
969 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
970 if (it == NULL) {
971 Py_DECREF(iters);
972 return NULL;
973 }
974 PyTuple_SET_ITEM(iters, i-1, it);
975 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 /* create mapobject structure */
978 lz = (mapobject *)type->tp_alloc(type, 0);
979 if (lz == NULL) {
980 Py_DECREF(iters);
981 return NULL;
982 }
983 lz->iters = iters;
984 func = PyTuple_GET_ITEM(args, 0);
985 Py_INCREF(func);
986 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000989}
990
991static void
992map_dealloc(mapobject *lz)
993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 PyObject_GC_UnTrack(lz);
995 Py_XDECREF(lz->iters);
996 Py_XDECREF(lz->func);
997 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +0000998}
999
1000static int
1001map_traverse(mapobject *lz, visitproc visit, void *arg)
1002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 Py_VISIT(lz->iters);
1004 Py_VISIT(lz->func);
1005 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001006}
1007
1008static PyObject *
1009map_next(mapobject *lz)
1010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 PyObject *val;
1012 PyObject *argtuple;
1013 PyObject *result;
1014 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 numargs = PyTuple_Size(lz->iters);
1017 argtuple = PyTuple_New(numargs);
1018 if (argtuple == NULL)
1019 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 for (i=0 ; i<numargs ; i++) {
1022 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1023 if (val == NULL) {
1024 Py_DECREF(argtuple);
1025 return NULL;
1026 }
1027 PyTuple_SET_ITEM(argtuple, i, val);
1028 }
1029 result = PyObject_Call(lz->func, argtuple, NULL);
1030 Py_DECREF(argtuple);
1031 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001032}
1033
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001034PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001035"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001036\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001037Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001039
Raymond Hettingera6c60372008-03-13 01:26:19 +00001040PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1042 "map", /* tp_name */
1043 sizeof(mapobject), /* tp_basicsize */
1044 0, /* tp_itemsize */
1045 /* methods */
1046 (destructor)map_dealloc, /* tp_dealloc */
1047 0, /* tp_print */
1048 0, /* tp_getattr */
1049 0, /* tp_setattr */
1050 0, /* tp_reserved */
1051 0, /* tp_repr */
1052 0, /* tp_as_number */
1053 0, /* tp_as_sequence */
1054 0, /* tp_as_mapping */
1055 0, /* tp_hash */
1056 0, /* tp_call */
1057 0, /* tp_str */
1058 PyObject_GenericGetAttr, /* tp_getattro */
1059 0, /* tp_setattro */
1060 0, /* tp_as_buffer */
1061 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1062 Py_TPFLAGS_BASETYPE, /* tp_flags */
1063 map_doc, /* tp_doc */
1064 (traverseproc)map_traverse, /* tp_traverse */
1065 0, /* tp_clear */
1066 0, /* tp_richcompare */
1067 0, /* tp_weaklistoffset */
1068 PyObject_SelfIter, /* tp_iter */
1069 (iternextfunc)map_next, /* tp_iternext */
1070 0, /* tp_methods */
1071 0, /* tp_members */
1072 0, /* tp_getset */
1073 0, /* tp_base */
1074 0, /* tp_dict */
1075 0, /* tp_descr_get */
1076 0, /* tp_descr_set */
1077 0, /* tp_dictoffset */
1078 0, /* tp_init */
1079 PyType_GenericAlloc, /* tp_alloc */
1080 map_new, /* tp_new */
1081 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001082};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001083
Guido van Rossum79f25d91997-04-29 20:08:16 +00001084static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001085builtin_next(PyObject *self, PyObject *args)
1086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 PyObject *it, *res;
1088 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1091 return NULL;
1092 if (!PyIter_Check(it)) {
1093 PyErr_Format(PyExc_TypeError,
1094 "%.200s object is not an iterator",
1095 it->ob_type->tp_name);
1096 return NULL;
1097 }
1098
1099 res = (*it->ob_type->tp_iternext)(it);
1100 if (res != NULL) {
1101 return res;
1102 } else if (def != NULL) {
1103 if (PyErr_Occurred()) {
1104 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1105 return NULL;
1106 PyErr_Clear();
1107 }
1108 Py_INCREF(def);
1109 return def;
1110 } else if (PyErr_Occurred()) {
1111 return NULL;
1112 } else {
1113 PyErr_SetNone(PyExc_StopIteration);
1114 return NULL;
1115 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001116}
1117
1118PyDoc_STRVAR(next_doc,
1119"next(iterator[, default])\n\
1120\n\
1121Return the next item from the iterator. If default is given and the iterator\n\
1122is exhausted, it is returned instead of raising StopIteration.");
1123
1124
1125static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001126builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 PyObject *v;
1129 PyObject *name;
1130 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1133 return NULL;
1134 if (PyObject_SetAttr(v, name, value) != 0)
1135 return NULL;
1136 Py_INCREF(Py_None);
1137 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001138}
1139
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001140PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001141"setattr(object, name, value)\n\
1142\n\
1143Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001144``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001145
1146
Guido van Rossum79f25d91997-04-29 20:08:16 +00001147static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001148builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 PyObject *v;
1151 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1154 return NULL;
1155 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1156 return NULL;
1157 Py_INCREF(Py_None);
1158 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001159}
1160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001161PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001162"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001163\n\
1164Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001165``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001166
1167
Guido van Rossum79f25d91997-04-29 20:08:16 +00001168static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001169builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001170{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001171 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 x = PyObject_Hash(v);
1174 if (x == -1)
1175 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001176 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001177}
1178
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001179PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001180"hash(object) -> integer\n\
1181\n\
1182Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001183the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001184
1185
Guido van Rossum79f25d91997-04-29 20:08:16 +00001186static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001187builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001190}
1191
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001192PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001193"hex(number) -> string\n\
1194\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001195Return the hexadecimal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001196
1197
Guido van Rossum79f25d91997-04-29 20:08:16 +00001198static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001199builtin_iter(PyObject *self, PyObject *args)
1200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1204 return NULL;
1205 if (w == NULL)
1206 return PyObject_GetIter(v);
1207 if (!PyCallable_Check(v)) {
1208 PyErr_SetString(PyExc_TypeError,
1209 "iter(v, w): v must be callable");
1210 return NULL;
1211 }
1212 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001213}
1214
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001215PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001216"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001217iter(callable, sentinel) -> iterator\n\
1218\n\
1219Get an iterator from an object. In the first form, the argument must\n\
1220supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001221In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001222
1223
1224static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001225builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 res = PyObject_Size(v);
1230 if (res < 0 && PyErr_Occurred())
1231 return NULL;
1232 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001233}
1234
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001235PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001236"len(object) -> integer\n\
1237\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001238Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001239
1240
Guido van Rossum79f25d91997-04-29 20:08:16 +00001241static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001242builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 d = PyEval_GetLocals();
1247 Py_XINCREF(d);
1248 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001249}
1250
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001251PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001252"locals() -> dictionary\n\
1253\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001254Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001255
1256
Guido van Rossum79f25d91997-04-29 20:08:16 +00001257static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001258min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1261 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (PyTuple_Size(args) > 1)
1264 v = args;
1265 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1266 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1269 keyfunc = PyDict_GetItemString(kwds, "key");
1270 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1271 PyErr_Format(PyExc_TypeError,
1272 "%s() got an unexpected keyword argument", name);
1273 return NULL;
1274 }
1275 Py_INCREF(keyfunc);
1276 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 it = PyObject_GetIter(v);
1279 if (it == NULL) {
1280 Py_XDECREF(keyfunc);
1281 return NULL;
1282 }
Tim Petersc3074532001-05-03 07:00:32 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 maxitem = NULL; /* the result */
1285 maxval = NULL; /* the value associated with the result */
1286 while (( item = PyIter_Next(it) )) {
1287 /* get the value from the key function */
1288 if (keyfunc != NULL) {
1289 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1290 if (val == NULL)
1291 goto Fail_it_item;
1292 }
1293 /* no key function; the value is the item */
1294 else {
1295 val = item;
1296 Py_INCREF(val);
1297 }
Tim Petersc3074532001-05-03 07:00:32 +00001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 /* maximum value and item are unset; set them */
1300 if (maxval == NULL) {
1301 maxitem = item;
1302 maxval = val;
1303 }
1304 /* maximum value and item are set; update them as necessary */
1305 else {
1306 int cmp = PyObject_RichCompareBool(val, maxval, op);
1307 if (cmp < 0)
1308 goto Fail_it_item_and_val;
1309 else if (cmp > 0) {
1310 Py_DECREF(maxval);
1311 Py_DECREF(maxitem);
1312 maxval = val;
1313 maxitem = item;
1314 }
1315 else {
1316 Py_DECREF(item);
1317 Py_DECREF(val);
1318 }
1319 }
1320 }
1321 if (PyErr_Occurred())
1322 goto Fail_it;
1323 if (maxval == NULL) {
1324 PyErr_Format(PyExc_ValueError,
1325 "%s() arg is an empty sequence", name);
1326 assert(maxitem == NULL);
1327 }
1328 else
1329 Py_DECREF(maxval);
1330 Py_DECREF(it);
1331 Py_XDECREF(keyfunc);
1332 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001333
1334Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001336Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001338Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 Py_XDECREF(maxval);
1340 Py_XDECREF(maxitem);
1341 Py_DECREF(it);
1342 Py_XDECREF(keyfunc);
1343 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001344}
1345
Guido van Rossum79f25d91997-04-29 20:08:16 +00001346static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001347builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001350}
1351
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001352PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001353"min(iterable[, key=func]) -> value\n\
1354min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001355\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001356With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001357With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001358
1359
Guido van Rossum79f25d91997-04-29 20:08:16 +00001360static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001361builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001364}
1365
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001366PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001367"max(iterable[, key=func]) -> value\n\
1368max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001369\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001370With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001371With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001372
1373
Guido van Rossum79f25d91997-04-29 20:08:16 +00001374static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001375builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001378}
1379
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001380PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001381"oct(number) -> string\n\
1382\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001383Return the octal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001384
1385
Guido van Rossum79f25d91997-04-29 20:08:16 +00001386static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001387builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 long ord;
1390 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 if (PyBytes_Check(obj)) {
1393 size = PyBytes_GET_SIZE(obj);
1394 if (size == 1) {
1395 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1396 return PyLong_FromLong(ord);
1397 }
1398 }
1399 else if (PyUnicode_Check(obj)) {
1400 size = PyUnicode_GET_SIZE(obj);
1401 if (size == 1) {
1402 ord = (long)*PyUnicode_AS_UNICODE(obj);
1403 return PyLong_FromLong(ord);
1404 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001405#ifndef Py_UNICODE_WIDE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 if (size == 2) {
1407 /* Decode a valid surrogate pair */
1408 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1409 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1410 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1411 0xDC00 <= c1 && c1 <= 0xDFFF) {
1412 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1413 0x00010000);
1414 return PyLong_FromLong(ord);
1415 }
1416 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001417#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 }
1419 else if (PyByteArray_Check(obj)) {
1420 /* XXX Hopefully this is temporary */
1421 size = PyByteArray_GET_SIZE(obj);
1422 if (size == 1) {
1423 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1424 return PyLong_FromLong(ord);
1425 }
1426 }
1427 else {
1428 PyErr_Format(PyExc_TypeError,
1429 "ord() expected string of length 1, but " \
1430 "%.200s found", obj->ob_type->tp_name);
1431 return NULL;
1432 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 PyErr_Format(PyExc_TypeError,
1435 "ord() expected a character, "
1436 "but string of length %zd found",
1437 size);
1438 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001439}
1440
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001441PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001442"ord(c) -> integer\n\
1443\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001444Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001445)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001446#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001447PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001448"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001449)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001450#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001451;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001452
1453
Guido van Rossum79f25d91997-04-29 20:08:16 +00001454static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001455builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1460 return NULL;
1461 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001462}
1463
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001464PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001465"pow(x, y[, z]) -> number\n\
1466\n\
1467With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001468equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001469
1470
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001471
Guido van Rossum34343512006-11-30 22:13:52 +00001472static PyObject *
1473builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 static char *kwlist[] = {"sep", "end", "file", 0};
1476 static PyObject *dummy_args;
1477 PyObject *sep = NULL, *end = NULL, *file = NULL;
1478 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 if (dummy_args == NULL) {
1481 if (!(dummy_args = PyTuple_New(0)))
1482 return NULL;
1483 }
1484 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1485 kwlist, &sep, &end, &file))
1486 return NULL;
1487 if (file == NULL || file == Py_None) {
1488 file = PySys_GetObject("stdout");
1489 /* sys.stdout may be None when FILE* stdout isn't connected */
1490 if (file == Py_None)
1491 Py_RETURN_NONE;
1492 }
Guido van Rossum34343512006-11-30 22:13:52 +00001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 if (sep == Py_None) {
1495 sep = NULL;
1496 }
1497 else if (sep && !PyUnicode_Check(sep)) {
1498 PyErr_Format(PyExc_TypeError,
1499 "sep must be None or a string, not %.200s",
1500 sep->ob_type->tp_name);
1501 return NULL;
1502 }
1503 if (end == Py_None) {
1504 end = NULL;
1505 }
1506 else if (end && !PyUnicode_Check(end)) {
1507 PyErr_Format(PyExc_TypeError,
1508 "end must be None or a string, not %.200s",
1509 end->ob_type->tp_name);
1510 return NULL;
1511 }
Guido van Rossum34343512006-11-30 22:13:52 +00001512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 for (i = 0; i < PyTuple_Size(args); i++) {
1514 if (i > 0) {
1515 if (sep == NULL)
1516 err = PyFile_WriteString(" ", file);
1517 else
1518 err = PyFile_WriteObject(sep, file,
1519 Py_PRINT_RAW);
1520 if (err)
1521 return NULL;
1522 }
1523 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1524 Py_PRINT_RAW);
1525 if (err)
1526 return NULL;
1527 }
Guido van Rossum34343512006-11-30 22:13:52 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 if (end == NULL)
1530 err = PyFile_WriteString("\n", file);
1531 else
1532 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1533 if (err)
1534 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001537}
1538
1539PyDoc_STRVAR(print_doc,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001540"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001541\n\
1542Prints the values to a stream, or to sys.stdout by default.\n\
1543Optional keyword arguments:\n\
1544file: a file-like object (stream); defaults to the current sys.stdout.\n\
1545sep: string inserted between values, default a space.\n\
1546end: string appended after the last value, default a newline.");
1547
1548
Guido van Rossuma88a0332007-02-26 16:59:55 +00001549static PyObject *
1550builtin_input(PyObject *self, PyObject *args)
1551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 PyObject *promptarg = NULL;
1553 PyObject *fin = PySys_GetObject("stdin");
1554 PyObject *fout = PySys_GetObject("stdout");
1555 PyObject *ferr = PySys_GetObject("stderr");
1556 PyObject *tmp;
1557 long fd;
1558 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 /* Parse arguments */
1561 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1562 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 /* Check that stdin/out/err are intact */
1565 if (fin == NULL || fin == Py_None) {
1566 PyErr_SetString(PyExc_RuntimeError,
1567 "input(): lost sys.stdin");
1568 return NULL;
1569 }
1570 if (fout == NULL || fout == Py_None) {
1571 PyErr_SetString(PyExc_RuntimeError,
1572 "input(): lost sys.stdout");
1573 return NULL;
1574 }
1575 if (ferr == NULL || ferr == Py_None) {
1576 PyErr_SetString(PyExc_RuntimeError,
1577 "input(): lost sys.stderr");
1578 return NULL;
1579 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 /* First of all, flush stderr */
1582 tmp = PyObject_CallMethod(ferr, "flush", "");
1583 if (tmp == NULL)
1584 PyErr_Clear();
1585 else
1586 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 /* We should only use (GNU) readline if Python's sys.stdin and
1589 sys.stdout are the same as C's stdin and stdout, because we
1590 need to pass it those. */
1591 tmp = PyObject_CallMethod(fin, "fileno", "");
1592 if (tmp == NULL) {
1593 PyErr_Clear();
1594 tty = 0;
1595 }
1596 else {
1597 fd = PyLong_AsLong(tmp);
1598 Py_DECREF(tmp);
1599 if (fd < 0 && PyErr_Occurred())
1600 return NULL;
1601 tty = fd == fileno(stdin) && isatty(fd);
1602 }
1603 if (tty) {
1604 tmp = PyObject_CallMethod(fout, "fileno", "");
1605 if (tmp == NULL)
1606 PyErr_Clear();
1607 else {
1608 fd = PyLong_AsLong(tmp);
1609 Py_DECREF(tmp);
1610 if (fd < 0 && PyErr_Occurred())
1611 return NULL;
1612 tty = fd == fileno(stdout) && isatty(fd);
1613 }
1614 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 /* If we're interactive, use (GNU) readline */
1617 if (tty) {
1618 PyObject *po;
1619 char *prompt;
1620 char *s;
1621 PyObject *stdin_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001622 char *stdin_encoding_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 PyObject *result;
Victor Stinner02bfdb32011-02-23 12:10:23 +00001624 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1627 if (!stdin_encoding)
1628 /* stdin is a text stream, so it must have an
1629 encoding. */
1630 return NULL;
Victor Stinner306f0102010-05-19 01:06:22 +00001631 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
1632 if (stdin_encoding_str == NULL) {
1633 Py_DECREF(stdin_encoding);
1634 return NULL;
1635 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 tmp = PyObject_CallMethod(fout, "flush", "");
1637 if (tmp == NULL)
1638 PyErr_Clear();
1639 else
1640 Py_DECREF(tmp);
1641 if (promptarg != NULL) {
1642 PyObject *stringpo;
1643 PyObject *stdout_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001644 char *stdout_encoding_str;
1645 stdout_encoding = PyObject_GetAttrString(fout, "encoding");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 if (stdout_encoding == NULL) {
1647 Py_DECREF(stdin_encoding);
1648 return NULL;
1649 }
Victor Stinner306f0102010-05-19 01:06:22 +00001650 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
1651 if (stdout_encoding_str == NULL) {
1652 Py_DECREF(stdin_encoding);
1653 Py_DECREF(stdout_encoding);
1654 return NULL;
1655 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 stringpo = PyObject_Str(promptarg);
1657 if (stringpo == NULL) {
1658 Py_DECREF(stdin_encoding);
1659 Py_DECREF(stdout_encoding);
1660 return NULL;
1661 }
1662 po = PyUnicode_AsEncodedString(stringpo,
Victor Stinner306f0102010-05-19 01:06:22 +00001663 stdout_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 Py_DECREF(stdout_encoding);
1665 Py_DECREF(stringpo);
1666 if (po == NULL) {
1667 Py_DECREF(stdin_encoding);
1668 return NULL;
1669 }
1670 prompt = PyBytes_AsString(po);
1671 if (prompt == NULL) {
1672 Py_DECREF(stdin_encoding);
1673 Py_DECREF(po);
1674 return NULL;
1675 }
1676 }
1677 else {
1678 po = NULL;
1679 prompt = "";
1680 }
1681 s = PyOS_Readline(stdin, stdout, prompt);
1682 Py_XDECREF(po);
1683 if (s == NULL) {
1684 if (!PyErr_Occurred())
1685 PyErr_SetNone(PyExc_KeyboardInterrupt);
1686 Py_DECREF(stdin_encoding);
1687 return NULL;
1688 }
Victor Stinner02bfdb32011-02-23 12:10:23 +00001689
1690 len = strlen(s);
1691 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 PyErr_SetNone(PyExc_EOFError);
1693 result = NULL;
1694 }
Victor Stinner02bfdb32011-02-23 12:10:23 +00001695 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 if (len > PY_SSIZE_T_MAX) {
1697 PyErr_SetString(PyExc_OverflowError,
1698 "input: input too long");
1699 result = NULL;
1700 }
1701 else {
Victor Stinner02bfdb32011-02-23 12:10:23 +00001702 len--; /* strip trailing '\n' */
1703 if (len != 0 && s[len-1] == '\r')
1704 len--; /* strip trailing '\r' */
1705 result = PyUnicode_Decode(s, len, stdin_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 }
1707 }
1708 Py_DECREF(stdin_encoding);
1709 PyMem_FREE(s);
1710 return result;
1711 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 /* Fallback if we're not interactive */
1714 if (promptarg != NULL) {
1715 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1716 return NULL;
1717 }
1718 tmp = PyObject_CallMethod(fout, "flush", "");
1719 if (tmp == NULL)
1720 PyErr_Clear();
1721 else
1722 Py_DECREF(tmp);
1723 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001724}
1725
1726PyDoc_STRVAR(input_doc,
1727"input([prompt]) -> string\n\
1728\n\
1729Read a string from standard input. The trailing newline is stripped.\n\
1730If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1731On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1732is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001733
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001734
Guido van Rossum79f25d91997-04-29 20:08:16 +00001735static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001736builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001739}
1740
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001741PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001742"repr(object) -> string\n\
1743\n\
1744Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001745For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001746
1747
Guido van Rossum79f25d91997-04-29 20:08:16 +00001748static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001749builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 static PyObject *round_str = NULL;
1752 PyObject *ndigits = NULL;
1753 static char *kwlist[] = {"number", "ndigits", 0};
1754 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1757 kwlist, &number, &ndigits))
1758 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 if (Py_TYPE(number)->tp_dict == NULL) {
1761 if (PyType_Ready(Py_TYPE(number)) < 0)
1762 return NULL;
1763 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 if (round_str == NULL) {
1766 round_str = PyUnicode_InternFromString("__round__");
1767 if (round_str == NULL)
1768 return NULL;
1769 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 round = _PyType_Lookup(Py_TYPE(number), round_str);
1772 if (round == NULL) {
1773 PyErr_Format(PyExc_TypeError,
1774 "type %.100s doesn't define __round__ method",
1775 Py_TYPE(number)->tp_name);
1776 return NULL;
1777 }
Alex Martelliae211f92007-08-22 23:21:33 +00001778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 if (ndigits == NULL)
1780 return PyObject_CallFunction(round, "O", number);
1781 else
1782 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001783}
1784
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001785PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001786"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001787\n\
1788Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001789This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001790same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001791
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001792
Raymond Hettinger64958a12003-12-17 20:43:33 +00001793static PyObject *
1794builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1797 PyObject *callable;
1798 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1799 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 /* args 1-3 should match listsort in Objects/listobject.c */
1802 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1803 kwlist, &seq, &keyfunc, &reverse))
1804 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 newlist = PySequence_List(seq);
1807 if (newlist == NULL)
1808 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 callable = PyObject_GetAttrString(newlist, "sort");
1811 if (callable == NULL) {
1812 Py_DECREF(newlist);
1813 return NULL;
1814 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 newargs = PyTuple_GetSlice(args, 1, 4);
1817 if (newargs == NULL) {
1818 Py_DECREF(newlist);
1819 Py_DECREF(callable);
1820 return NULL;
1821 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 v = PyObject_Call(callable, newargs, kwds);
1824 Py_DECREF(newargs);
1825 Py_DECREF(callable);
1826 if (v == NULL) {
1827 Py_DECREF(newlist);
1828 return NULL;
1829 }
1830 Py_DECREF(v);
1831 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001832}
1833
1834PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001835"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001836
Guido van Rossum79f25d91997-04-29 20:08:16 +00001837static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001838builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 PyObject *v = NULL;
1841 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1844 return NULL;
1845 if (v == NULL) {
1846 d = PyEval_GetLocals();
1847 if (d == NULL) {
1848 if (!PyErr_Occurred())
1849 PyErr_SetString(PyExc_SystemError,
1850 "vars(): no locals!?");
1851 }
1852 else
1853 Py_INCREF(d);
1854 }
1855 else {
1856 d = PyObject_GetAttrString(v, "__dict__");
1857 if (d == NULL) {
1858 PyErr_SetString(PyExc_TypeError,
1859 "vars() argument must have __dict__ attribute");
1860 return NULL;
1861 }
1862 }
1863 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001864}
1865
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001866PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001867"vars([object]) -> dictionary\n\
1868\n\
1869Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001870With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001871
Alex Martellia70b1912003-04-22 08:12:33 +00001872static PyObject*
1873builtin_sum(PyObject *self, PyObject *args)
1874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 PyObject *seq;
1876 PyObject *result = NULL;
1877 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1880 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 iter = PyObject_GetIter(seq);
1883 if (iter == NULL)
1884 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 if (result == NULL) {
1887 result = PyLong_FromLong(0);
1888 if (result == NULL) {
1889 Py_DECREF(iter);
1890 return NULL;
1891 }
1892 } else {
1893 /* reject string values for 'start' parameter */
1894 if (PyUnicode_Check(result)) {
1895 PyErr_SetString(PyExc_TypeError,
1896 "sum() can't sum strings [use ''.join(seq) instead]");
1897 Py_DECREF(iter);
1898 return NULL;
1899 }
1900 if (PyByteArray_Check(result)) {
1901 PyErr_SetString(PyExc_TypeError,
1902 "sum() can't sum bytes [use b''.join(seq) instead]");
1903 Py_DECREF(iter);
1904 return NULL;
1905 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 Py_INCREF(result);
1908 }
Alex Martellia70b1912003-04-22 08:12:33 +00001909
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001910#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1912 Assumes all inputs are the same type. If the assumption fails, default
1913 to the more general routine.
1914 */
1915 if (PyLong_CheckExact(result)) {
1916 int overflow;
1917 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1918 /* If this already overflowed, don't even enter the loop. */
1919 if (overflow == 0) {
1920 Py_DECREF(result);
1921 result = NULL;
1922 }
1923 while(result == NULL) {
1924 item = PyIter_Next(iter);
1925 if (item == NULL) {
1926 Py_DECREF(iter);
1927 if (PyErr_Occurred())
1928 return NULL;
1929 return PyLong_FromLong(i_result);
1930 }
1931 if (PyLong_CheckExact(item)) {
1932 long b = PyLong_AsLongAndOverflow(item, &overflow);
1933 long x = i_result + b;
1934 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1935 i_result = x;
1936 Py_DECREF(item);
1937 continue;
1938 }
1939 }
1940 /* Either overflowed or is not an int. Restore real objects and process normally */
1941 result = PyLong_FromLong(i_result);
1942 temp = PyNumber_Add(result, item);
1943 Py_DECREF(result);
1944 Py_DECREF(item);
1945 result = temp;
1946 if (result == NULL) {
1947 Py_DECREF(iter);
1948 return NULL;
1949 }
1950 }
1951 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 if (PyFloat_CheckExact(result)) {
1954 double f_result = PyFloat_AS_DOUBLE(result);
1955 Py_DECREF(result);
1956 result = NULL;
1957 while(result == NULL) {
1958 item = PyIter_Next(iter);
1959 if (item == NULL) {
1960 Py_DECREF(iter);
1961 if (PyErr_Occurred())
1962 return NULL;
1963 return PyFloat_FromDouble(f_result);
1964 }
1965 if (PyFloat_CheckExact(item)) {
1966 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1967 f_result += PyFloat_AS_DOUBLE(item);
1968 PyFPE_END_PROTECT(f_result)
1969 Py_DECREF(item);
1970 continue;
1971 }
1972 if (PyLong_CheckExact(item)) {
1973 long value;
1974 int overflow;
1975 value = PyLong_AsLongAndOverflow(item, &overflow);
1976 if (!overflow) {
1977 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1978 f_result += (double)value;
1979 PyFPE_END_PROTECT(f_result)
1980 Py_DECREF(item);
1981 continue;
1982 }
1983 }
1984 result = PyFloat_FromDouble(f_result);
1985 temp = PyNumber_Add(result, item);
1986 Py_DECREF(result);
1987 Py_DECREF(item);
1988 result = temp;
1989 if (result == NULL) {
1990 Py_DECREF(iter);
1991 return NULL;
1992 }
1993 }
1994 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001995#endif
1996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 for(;;) {
1998 item = PyIter_Next(iter);
1999 if (item == NULL) {
2000 /* error, or end-of-sequence */
2001 if (PyErr_Occurred()) {
2002 Py_DECREF(result);
2003 result = NULL;
2004 }
2005 break;
2006 }
2007 /* It's tempting to use PyNumber_InPlaceAdd instead of
2008 PyNumber_Add here, to avoid quadratic running time
2009 when doing 'sum(list_of_lists, [])'. However, this
2010 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 empty = []
2013 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 would change the value of empty. */
2016 temp = PyNumber_Add(result, item);
2017 Py_DECREF(result);
2018 Py_DECREF(item);
2019 result = temp;
2020 if (result == NULL)
2021 break;
2022 }
2023 Py_DECREF(iter);
2024 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002025}
2026
2027PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002028"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002029\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002030Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2031of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002032empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002033
2034
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002035static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002036builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 PyObject *inst;
2039 PyObject *cls;
2040 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2043 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 retval = PyObject_IsInstance(inst, cls);
2046 if (retval < 0)
2047 return NULL;
2048 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002049}
2050
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002051PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002052"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002053\n\
2054Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002055With a type as second argument, return whether that is the object's type.\n\
2056The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002057isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002058
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002059
2060static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002061builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 PyObject *derived;
2064 PyObject *cls;
2065 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2068 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 retval = PyObject_IsSubclass(derived, cls);
2071 if (retval < 0)
2072 return NULL;
2073 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002074}
2075
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002076PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002077"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002078\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002079Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2080When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2081is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002082
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002083
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002084typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 PyObject_HEAD
2086 Py_ssize_t tuplesize;
2087 PyObject *ittuple; /* tuple of iterators */
2088 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002089} zipobject;
2090
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002091static PyObject *
2092zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 zipobject *lz;
2095 Py_ssize_t i;
2096 PyObject *ittuple; /* tuple of iterators */
2097 PyObject *result;
2098 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2101 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 /* args must be a tuple */
2104 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 /* obtain iterators */
2107 ittuple = PyTuple_New(tuplesize);
2108 if (ittuple == NULL)
2109 return NULL;
2110 for (i=0; i < tuplesize; ++i) {
2111 PyObject *item = PyTuple_GET_ITEM(args, i);
2112 PyObject *it = PyObject_GetIter(item);
2113 if (it == NULL) {
2114 if (PyErr_ExceptionMatches(PyExc_TypeError))
2115 PyErr_Format(PyExc_TypeError,
2116 "zip argument #%zd must support iteration",
2117 i+1);
2118 Py_DECREF(ittuple);
2119 return NULL;
2120 }
2121 PyTuple_SET_ITEM(ittuple, i, it);
2122 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 /* create a result holder */
2125 result = PyTuple_New(tuplesize);
2126 if (result == NULL) {
2127 Py_DECREF(ittuple);
2128 return NULL;
2129 }
2130 for (i=0 ; i < tuplesize ; i++) {
2131 Py_INCREF(Py_None);
2132 PyTuple_SET_ITEM(result, i, Py_None);
2133 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 /* create zipobject structure */
2136 lz = (zipobject *)type->tp_alloc(type, 0);
2137 if (lz == NULL) {
2138 Py_DECREF(ittuple);
2139 Py_DECREF(result);
2140 return NULL;
2141 }
2142 lz->ittuple = ittuple;
2143 lz->tuplesize = tuplesize;
2144 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002147}
2148
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002149static void
2150zip_dealloc(zipobject *lz)
2151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 PyObject_GC_UnTrack(lz);
2153 Py_XDECREF(lz->ittuple);
2154 Py_XDECREF(lz->result);
2155 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002156}
2157
2158static int
2159zip_traverse(zipobject *lz, visitproc visit, void *arg)
2160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 Py_VISIT(lz->ittuple);
2162 Py_VISIT(lz->result);
2163 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002164}
2165
2166static PyObject *
2167zip_next(zipobject *lz)
2168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 Py_ssize_t i;
2170 Py_ssize_t tuplesize = lz->tuplesize;
2171 PyObject *result = lz->result;
2172 PyObject *it;
2173 PyObject *item;
2174 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 if (tuplesize == 0)
2177 return NULL;
2178 if (Py_REFCNT(result) == 1) {
2179 Py_INCREF(result);
2180 for (i=0 ; i < tuplesize ; i++) {
2181 it = PyTuple_GET_ITEM(lz->ittuple, i);
2182 item = (*Py_TYPE(it)->tp_iternext)(it);
2183 if (item == NULL) {
2184 Py_DECREF(result);
2185 return NULL;
2186 }
2187 olditem = PyTuple_GET_ITEM(result, i);
2188 PyTuple_SET_ITEM(result, i, item);
2189 Py_DECREF(olditem);
2190 }
2191 } else {
2192 result = PyTuple_New(tuplesize);
2193 if (result == NULL)
2194 return NULL;
2195 for (i=0 ; i < tuplesize ; i++) {
2196 it = PyTuple_GET_ITEM(lz->ittuple, i);
2197 item = (*Py_TYPE(it)->tp_iternext)(it);
2198 if (item == NULL) {
2199 Py_DECREF(result);
2200 return NULL;
2201 }
2202 PyTuple_SET_ITEM(result, i, item);
2203 }
2204 }
2205 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002206}
Barry Warsawbd599b52000-08-03 15:45:29 +00002207
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002208PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002209"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002210\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002211Return a zip object whose .__next__() method returns a tuple where\n\
2212the i-th element comes from the i-th iterable argument. The .__next__()\n\
2213method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002214is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002215
2216PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2218 "zip", /* tp_name */
2219 sizeof(zipobject), /* tp_basicsize */
2220 0, /* tp_itemsize */
2221 /* methods */
2222 (destructor)zip_dealloc, /* tp_dealloc */
2223 0, /* tp_print */
2224 0, /* tp_getattr */
2225 0, /* tp_setattr */
2226 0, /* tp_reserved */
2227 0, /* tp_repr */
2228 0, /* tp_as_number */
2229 0, /* tp_as_sequence */
2230 0, /* tp_as_mapping */
2231 0, /* tp_hash */
2232 0, /* tp_call */
2233 0, /* tp_str */
2234 PyObject_GenericGetAttr, /* tp_getattro */
2235 0, /* tp_setattro */
2236 0, /* tp_as_buffer */
2237 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2238 Py_TPFLAGS_BASETYPE, /* tp_flags */
2239 zip_doc, /* tp_doc */
2240 (traverseproc)zip_traverse, /* tp_traverse */
2241 0, /* tp_clear */
2242 0, /* tp_richcompare */
2243 0, /* tp_weaklistoffset */
2244 PyObject_SelfIter, /* tp_iter */
2245 (iternextfunc)zip_next, /* tp_iternext */
2246 0, /* tp_methods */
2247 0, /* tp_members */
2248 0, /* tp_getset */
2249 0, /* tp_base */
2250 0, /* tp_dict */
2251 0, /* tp_descr_get */
2252 0, /* tp_descr_set */
2253 0, /* tp_dictoffset */
2254 0, /* tp_init */
2255 PyType_GenericAlloc, /* tp_alloc */
2256 zip_new, /* tp_new */
2257 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002258};
Barry Warsawbd599b52000-08-03 15:45:29 +00002259
2260
Guido van Rossum79f25d91997-04-29 20:08:16 +00002261static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 {"__build_class__", (PyCFunction)builtin___build_class__,
2263 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2264 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2265 {"abs", builtin_abs, METH_O, abs_doc},
2266 {"all", builtin_all, METH_O, all_doc},
2267 {"any", builtin_any, METH_O, any_doc},
2268 {"ascii", builtin_ascii, METH_O, ascii_doc},
2269 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002270 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2272 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2273 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2274 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2275 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2276 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2277 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2278 {"format", builtin_format, METH_VARARGS, format_doc},
2279 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2280 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2281 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2282 {"hash", builtin_hash, METH_O, hash_doc},
2283 {"hex", builtin_hex, METH_O, hex_doc},
2284 {"id", builtin_id, METH_O, id_doc},
2285 {"input", builtin_input, METH_VARARGS, input_doc},
2286 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2287 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2288 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2289 {"len", builtin_len, METH_O, len_doc},
2290 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2291 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2292 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2293 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2294 {"oct", builtin_oct, METH_O, oct_doc},
2295 {"ord", builtin_ord, METH_O, ord_doc},
2296 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2297 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2298 {"repr", builtin_repr, METH_O, repr_doc},
2299 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2300 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2301 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2302 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2303 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2304 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002305};
2306
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002307PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002308"Built-in functions, exceptions, and other objects.\n\
2309\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002310Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002311
Martin v. Löwis1a214512008-06-11 05:26:20 +00002312static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 PyModuleDef_HEAD_INIT,
2314 "builtins",
2315 builtin_doc,
2316 -1, /* multiple "initialization" just copies the module dict. */
2317 builtin_methods,
2318 NULL,
2319 NULL,
2320 NULL,
2321 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002322};
2323
2324
Guido van Rossum25ce5661997-08-02 03:10:38 +00002325PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002326_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 PyObject *mod, *dict, *debug;
2329 mod = PyModule_Create(&builtinsmodule);
2330 if (mod == NULL)
2331 return NULL;
2332 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002333
Tim Peters7571a0f2003-03-23 17:52:28 +00002334#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 /* "builtins" exposes a number of statically allocated objects
2336 * that, before this code was added in 2.3, never showed up in
2337 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2338 * result, programs leaking references to None and False (etc)
2339 * couldn't be diagnosed by examining sys.getobjects(0).
2340 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002341#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2342#else
2343#define ADD_TO_ALL(OBJECT) (void)0
2344#endif
2345
Tim Peters4b7625e2001-09-13 21:37:17 +00002346#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2348 return NULL; \
2349 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 SETBUILTIN("None", Py_None);
2352 SETBUILTIN("Ellipsis", Py_Ellipsis);
2353 SETBUILTIN("NotImplemented", Py_NotImplemented);
2354 SETBUILTIN("False", Py_False);
2355 SETBUILTIN("True", Py_True);
2356 SETBUILTIN("bool", &PyBool_Type);
2357 SETBUILTIN("memoryview", &PyMemoryView_Type);
2358 SETBUILTIN("bytearray", &PyByteArray_Type);
2359 SETBUILTIN("bytes", &PyBytes_Type);
2360 SETBUILTIN("classmethod", &PyClassMethod_Type);
2361 SETBUILTIN("complex", &PyComplex_Type);
2362 SETBUILTIN("dict", &PyDict_Type);
2363 SETBUILTIN("enumerate", &PyEnum_Type);
2364 SETBUILTIN("filter", &PyFilter_Type);
2365 SETBUILTIN("float", &PyFloat_Type);
2366 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2367 SETBUILTIN("property", &PyProperty_Type);
2368 SETBUILTIN("int", &PyLong_Type);
2369 SETBUILTIN("list", &PyList_Type);
2370 SETBUILTIN("map", &PyMap_Type);
2371 SETBUILTIN("object", &PyBaseObject_Type);
2372 SETBUILTIN("range", &PyRange_Type);
2373 SETBUILTIN("reversed", &PyReversed_Type);
2374 SETBUILTIN("set", &PySet_Type);
2375 SETBUILTIN("slice", &PySlice_Type);
2376 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2377 SETBUILTIN("str", &PyUnicode_Type);
2378 SETBUILTIN("super", &PySuper_Type);
2379 SETBUILTIN("tuple", &PyTuple_Type);
2380 SETBUILTIN("type", &PyType_Type);
2381 SETBUILTIN("zip", &PyZip_Type);
2382 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2383 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2384 Py_XDECREF(debug);
2385 return NULL;
2386 }
2387 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002390#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002391#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002392}