blob: f9b3202d54e370752aff921656865919fc9fd144 [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\
310Return the binary representation of an integer or long integer.");
311
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\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001195Return the hexadecimal representation of an integer or long 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\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001383Return the octal representation of an integer or long 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;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1626 if (!stdin_encoding)
1627 /* stdin is a text stream, so it must have an
1628 encoding. */
1629 return NULL;
Victor Stinner306f0102010-05-19 01:06:22 +00001630 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
1631 if (stdin_encoding_str == NULL) {
1632 Py_DECREF(stdin_encoding);
1633 return NULL;
1634 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 tmp = PyObject_CallMethod(fout, "flush", "");
1636 if (tmp == NULL)
1637 PyErr_Clear();
1638 else
1639 Py_DECREF(tmp);
1640 if (promptarg != NULL) {
1641 PyObject *stringpo;
1642 PyObject *stdout_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001643 char *stdout_encoding_str;
1644 stdout_encoding = PyObject_GetAttrString(fout, "encoding");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 if (stdout_encoding == NULL) {
1646 Py_DECREF(stdin_encoding);
1647 return NULL;
1648 }
Victor Stinner306f0102010-05-19 01:06:22 +00001649 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
1650 if (stdout_encoding_str == NULL) {
1651 Py_DECREF(stdin_encoding);
1652 Py_DECREF(stdout_encoding);
1653 return NULL;
1654 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 stringpo = PyObject_Str(promptarg);
1656 if (stringpo == NULL) {
1657 Py_DECREF(stdin_encoding);
1658 Py_DECREF(stdout_encoding);
1659 return NULL;
1660 }
1661 po = PyUnicode_AsEncodedString(stringpo,
Victor Stinner306f0102010-05-19 01:06:22 +00001662 stdout_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 Py_DECREF(stdout_encoding);
1664 Py_DECREF(stringpo);
1665 if (po == NULL) {
1666 Py_DECREF(stdin_encoding);
1667 return NULL;
1668 }
1669 prompt = PyBytes_AsString(po);
1670 if (prompt == NULL) {
1671 Py_DECREF(stdin_encoding);
1672 Py_DECREF(po);
1673 return NULL;
1674 }
1675 }
1676 else {
1677 po = NULL;
1678 prompt = "";
1679 }
1680 s = PyOS_Readline(stdin, stdout, prompt);
1681 Py_XDECREF(po);
1682 if (s == NULL) {
1683 if (!PyErr_Occurred())
1684 PyErr_SetNone(PyExc_KeyboardInterrupt);
1685 Py_DECREF(stdin_encoding);
1686 return NULL;
1687 }
1688 if (*s == '\0') {
1689 PyErr_SetNone(PyExc_EOFError);
1690 result = NULL;
1691 }
1692 else { /* strip trailing '\n' */
1693 size_t len = strlen(s);
1694 if (len > PY_SSIZE_T_MAX) {
1695 PyErr_SetString(PyExc_OverflowError,
1696 "input: input too long");
1697 result = NULL;
1698 }
1699 else {
Victor Stinner306f0102010-05-19 01:06:22 +00001700 result = PyUnicode_Decode(s, len-1, stdin_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 }
1702 }
1703 Py_DECREF(stdin_encoding);
1704 PyMem_FREE(s);
1705 return result;
1706 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 /* Fallback if we're not interactive */
1709 if (promptarg != NULL) {
1710 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1711 return NULL;
1712 }
1713 tmp = PyObject_CallMethod(fout, "flush", "");
1714 if (tmp == NULL)
1715 PyErr_Clear();
1716 else
1717 Py_DECREF(tmp);
1718 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001719}
1720
1721PyDoc_STRVAR(input_doc,
1722"input([prompt]) -> string\n\
1723\n\
1724Read a string from standard input. The trailing newline is stripped.\n\
1725If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1726On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1727is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001728
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001729
Guido van Rossum79f25d91997-04-29 20:08:16 +00001730static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001731builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001734}
1735
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001736PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001737"repr(object) -> string\n\
1738\n\
1739Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001740For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001741
1742
Guido van Rossum79f25d91997-04-29 20:08:16 +00001743static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001744builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 static PyObject *round_str = NULL;
1747 PyObject *ndigits = NULL;
1748 static char *kwlist[] = {"number", "ndigits", 0};
1749 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1752 kwlist, &number, &ndigits))
1753 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 if (Py_TYPE(number)->tp_dict == NULL) {
1756 if (PyType_Ready(Py_TYPE(number)) < 0)
1757 return NULL;
1758 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 if (round_str == NULL) {
1761 round_str = PyUnicode_InternFromString("__round__");
1762 if (round_str == NULL)
1763 return NULL;
1764 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 round = _PyType_Lookup(Py_TYPE(number), round_str);
1767 if (round == NULL) {
1768 PyErr_Format(PyExc_TypeError,
1769 "type %.100s doesn't define __round__ method",
1770 Py_TYPE(number)->tp_name);
1771 return NULL;
1772 }
Alex Martelliae211f92007-08-22 23:21:33 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 if (ndigits == NULL)
1775 return PyObject_CallFunction(round, "O", number);
1776 else
1777 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001778}
1779
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001780PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001781"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001782\n\
1783Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001784This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001785same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001786
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001787
Raymond Hettinger64958a12003-12-17 20:43:33 +00001788static PyObject *
1789builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1792 PyObject *callable;
1793 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1794 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 /* args 1-3 should match listsort in Objects/listobject.c */
1797 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1798 kwlist, &seq, &keyfunc, &reverse))
1799 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 newlist = PySequence_List(seq);
1802 if (newlist == NULL)
1803 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 callable = PyObject_GetAttrString(newlist, "sort");
1806 if (callable == NULL) {
1807 Py_DECREF(newlist);
1808 return NULL;
1809 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 newargs = PyTuple_GetSlice(args, 1, 4);
1812 if (newargs == NULL) {
1813 Py_DECREF(newlist);
1814 Py_DECREF(callable);
1815 return NULL;
1816 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 v = PyObject_Call(callable, newargs, kwds);
1819 Py_DECREF(newargs);
1820 Py_DECREF(callable);
1821 if (v == NULL) {
1822 Py_DECREF(newlist);
1823 return NULL;
1824 }
1825 Py_DECREF(v);
1826 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001827}
1828
1829PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001830"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001831
Guido van Rossum79f25d91997-04-29 20:08:16 +00001832static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001833builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 PyObject *v = NULL;
1836 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1839 return NULL;
1840 if (v == NULL) {
1841 d = PyEval_GetLocals();
1842 if (d == NULL) {
1843 if (!PyErr_Occurred())
1844 PyErr_SetString(PyExc_SystemError,
1845 "vars(): no locals!?");
1846 }
1847 else
1848 Py_INCREF(d);
1849 }
1850 else {
1851 d = PyObject_GetAttrString(v, "__dict__");
1852 if (d == NULL) {
1853 PyErr_SetString(PyExc_TypeError,
1854 "vars() argument must have __dict__ attribute");
1855 return NULL;
1856 }
1857 }
1858 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001859}
1860
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001861PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001862"vars([object]) -> dictionary\n\
1863\n\
1864Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001865With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001866
Alex Martellia70b1912003-04-22 08:12:33 +00001867static PyObject*
1868builtin_sum(PyObject *self, PyObject *args)
1869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 PyObject *seq;
1871 PyObject *result = NULL;
1872 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1875 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 iter = PyObject_GetIter(seq);
1878 if (iter == NULL)
1879 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 if (result == NULL) {
1882 result = PyLong_FromLong(0);
1883 if (result == NULL) {
1884 Py_DECREF(iter);
1885 return NULL;
1886 }
1887 } else {
1888 /* reject string values for 'start' parameter */
1889 if (PyUnicode_Check(result)) {
1890 PyErr_SetString(PyExc_TypeError,
1891 "sum() can't sum strings [use ''.join(seq) instead]");
1892 Py_DECREF(iter);
1893 return NULL;
1894 }
1895 if (PyByteArray_Check(result)) {
1896 PyErr_SetString(PyExc_TypeError,
1897 "sum() can't sum bytes [use b''.join(seq) instead]");
1898 Py_DECREF(iter);
1899 return NULL;
1900 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 Py_INCREF(result);
1903 }
Alex Martellia70b1912003-04-22 08:12:33 +00001904
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001905#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1907 Assumes all inputs are the same type. If the assumption fails, default
1908 to the more general routine.
1909 */
1910 if (PyLong_CheckExact(result)) {
1911 int overflow;
1912 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1913 /* If this already overflowed, don't even enter the loop. */
1914 if (overflow == 0) {
1915 Py_DECREF(result);
1916 result = NULL;
1917 }
1918 while(result == NULL) {
1919 item = PyIter_Next(iter);
1920 if (item == NULL) {
1921 Py_DECREF(iter);
1922 if (PyErr_Occurred())
1923 return NULL;
1924 return PyLong_FromLong(i_result);
1925 }
1926 if (PyLong_CheckExact(item)) {
1927 long b = PyLong_AsLongAndOverflow(item, &overflow);
1928 long x = i_result + b;
1929 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1930 i_result = x;
1931 Py_DECREF(item);
1932 continue;
1933 }
1934 }
1935 /* Either overflowed or is not an int. Restore real objects and process normally */
1936 result = PyLong_FromLong(i_result);
1937 temp = PyNumber_Add(result, item);
1938 Py_DECREF(result);
1939 Py_DECREF(item);
1940 result = temp;
1941 if (result == NULL) {
1942 Py_DECREF(iter);
1943 return NULL;
1944 }
1945 }
1946 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 if (PyFloat_CheckExact(result)) {
1949 double f_result = PyFloat_AS_DOUBLE(result);
1950 Py_DECREF(result);
1951 result = NULL;
1952 while(result == NULL) {
1953 item = PyIter_Next(iter);
1954 if (item == NULL) {
1955 Py_DECREF(iter);
1956 if (PyErr_Occurred())
1957 return NULL;
1958 return PyFloat_FromDouble(f_result);
1959 }
1960 if (PyFloat_CheckExact(item)) {
1961 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1962 f_result += PyFloat_AS_DOUBLE(item);
1963 PyFPE_END_PROTECT(f_result)
1964 Py_DECREF(item);
1965 continue;
1966 }
1967 if (PyLong_CheckExact(item)) {
1968 long value;
1969 int overflow;
1970 value = PyLong_AsLongAndOverflow(item, &overflow);
1971 if (!overflow) {
1972 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1973 f_result += (double)value;
1974 PyFPE_END_PROTECT(f_result)
1975 Py_DECREF(item);
1976 continue;
1977 }
1978 }
1979 result = PyFloat_FromDouble(f_result);
1980 temp = PyNumber_Add(result, item);
1981 Py_DECREF(result);
1982 Py_DECREF(item);
1983 result = temp;
1984 if (result == NULL) {
1985 Py_DECREF(iter);
1986 return NULL;
1987 }
1988 }
1989 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001990#endif
1991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 for(;;) {
1993 item = PyIter_Next(iter);
1994 if (item == NULL) {
1995 /* error, or end-of-sequence */
1996 if (PyErr_Occurred()) {
1997 Py_DECREF(result);
1998 result = NULL;
1999 }
2000 break;
2001 }
2002 /* It's tempting to use PyNumber_InPlaceAdd instead of
2003 PyNumber_Add here, to avoid quadratic running time
2004 when doing 'sum(list_of_lists, [])'. However, this
2005 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 empty = []
2008 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 would change the value of empty. */
2011 temp = PyNumber_Add(result, item);
2012 Py_DECREF(result);
2013 Py_DECREF(item);
2014 result = temp;
2015 if (result == NULL)
2016 break;
2017 }
2018 Py_DECREF(iter);
2019 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002020}
2021
2022PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002023"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002024\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002025Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2026of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002027empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002028
2029
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002030static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002031builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 PyObject *inst;
2034 PyObject *cls;
2035 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2038 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 retval = PyObject_IsInstance(inst, cls);
2041 if (retval < 0)
2042 return NULL;
2043 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002044}
2045
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002046PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002047"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002048\n\
2049Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002050With a type as second argument, return whether that is the object's type.\n\
2051The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002052isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002053
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002054
2055static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002056builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 PyObject *derived;
2059 PyObject *cls;
2060 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2063 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 retval = PyObject_IsSubclass(derived, cls);
2066 if (retval < 0)
2067 return NULL;
2068 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002069}
2070
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002071PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002072"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002073\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002074Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2075When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2076is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002077
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002078
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002079typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 PyObject_HEAD
2081 Py_ssize_t tuplesize;
2082 PyObject *ittuple; /* tuple of iterators */
2083 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002084} zipobject;
2085
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002086static PyObject *
2087zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 zipobject *lz;
2090 Py_ssize_t i;
2091 PyObject *ittuple; /* tuple of iterators */
2092 PyObject *result;
2093 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2096 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 /* args must be a tuple */
2099 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 /* obtain iterators */
2102 ittuple = PyTuple_New(tuplesize);
2103 if (ittuple == NULL)
2104 return NULL;
2105 for (i=0; i < tuplesize; ++i) {
2106 PyObject *item = PyTuple_GET_ITEM(args, i);
2107 PyObject *it = PyObject_GetIter(item);
2108 if (it == NULL) {
2109 if (PyErr_ExceptionMatches(PyExc_TypeError))
2110 PyErr_Format(PyExc_TypeError,
2111 "zip argument #%zd must support iteration",
2112 i+1);
2113 Py_DECREF(ittuple);
2114 return NULL;
2115 }
2116 PyTuple_SET_ITEM(ittuple, i, it);
2117 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 /* create a result holder */
2120 result = PyTuple_New(tuplesize);
2121 if (result == NULL) {
2122 Py_DECREF(ittuple);
2123 return NULL;
2124 }
2125 for (i=0 ; i < tuplesize ; i++) {
2126 Py_INCREF(Py_None);
2127 PyTuple_SET_ITEM(result, i, Py_None);
2128 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 /* create zipobject structure */
2131 lz = (zipobject *)type->tp_alloc(type, 0);
2132 if (lz == NULL) {
2133 Py_DECREF(ittuple);
2134 Py_DECREF(result);
2135 return NULL;
2136 }
2137 lz->ittuple = ittuple;
2138 lz->tuplesize = tuplesize;
2139 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002142}
2143
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002144static void
2145zip_dealloc(zipobject *lz)
2146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 PyObject_GC_UnTrack(lz);
2148 Py_XDECREF(lz->ittuple);
2149 Py_XDECREF(lz->result);
2150 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002151}
2152
2153static int
2154zip_traverse(zipobject *lz, visitproc visit, void *arg)
2155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 Py_VISIT(lz->ittuple);
2157 Py_VISIT(lz->result);
2158 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002159}
2160
2161static PyObject *
2162zip_next(zipobject *lz)
2163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 Py_ssize_t i;
2165 Py_ssize_t tuplesize = lz->tuplesize;
2166 PyObject *result = lz->result;
2167 PyObject *it;
2168 PyObject *item;
2169 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 if (tuplesize == 0)
2172 return NULL;
2173 if (Py_REFCNT(result) == 1) {
2174 Py_INCREF(result);
2175 for (i=0 ; i < tuplesize ; i++) {
2176 it = PyTuple_GET_ITEM(lz->ittuple, i);
2177 item = (*Py_TYPE(it)->tp_iternext)(it);
2178 if (item == NULL) {
2179 Py_DECREF(result);
2180 return NULL;
2181 }
2182 olditem = PyTuple_GET_ITEM(result, i);
2183 PyTuple_SET_ITEM(result, i, item);
2184 Py_DECREF(olditem);
2185 }
2186 } else {
2187 result = PyTuple_New(tuplesize);
2188 if (result == NULL)
2189 return NULL;
2190 for (i=0 ; i < tuplesize ; i++) {
2191 it = PyTuple_GET_ITEM(lz->ittuple, i);
2192 item = (*Py_TYPE(it)->tp_iternext)(it);
2193 if (item == NULL) {
2194 Py_DECREF(result);
2195 return NULL;
2196 }
2197 PyTuple_SET_ITEM(result, i, item);
2198 }
2199 }
2200 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002201}
Barry Warsawbd599b52000-08-03 15:45:29 +00002202
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002203PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002204"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002205\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002206Return a zip object whose .__next__() method returns a tuple where\n\
2207the i-th element comes from the i-th iterable argument. The .__next__()\n\
2208method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002209is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002210
2211PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2213 "zip", /* tp_name */
2214 sizeof(zipobject), /* tp_basicsize */
2215 0, /* tp_itemsize */
2216 /* methods */
2217 (destructor)zip_dealloc, /* tp_dealloc */
2218 0, /* tp_print */
2219 0, /* tp_getattr */
2220 0, /* tp_setattr */
2221 0, /* tp_reserved */
2222 0, /* tp_repr */
2223 0, /* tp_as_number */
2224 0, /* tp_as_sequence */
2225 0, /* tp_as_mapping */
2226 0, /* tp_hash */
2227 0, /* tp_call */
2228 0, /* tp_str */
2229 PyObject_GenericGetAttr, /* tp_getattro */
2230 0, /* tp_setattro */
2231 0, /* tp_as_buffer */
2232 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2233 Py_TPFLAGS_BASETYPE, /* tp_flags */
2234 zip_doc, /* tp_doc */
2235 (traverseproc)zip_traverse, /* tp_traverse */
2236 0, /* tp_clear */
2237 0, /* tp_richcompare */
2238 0, /* tp_weaklistoffset */
2239 PyObject_SelfIter, /* tp_iter */
2240 (iternextfunc)zip_next, /* tp_iternext */
2241 0, /* tp_methods */
2242 0, /* tp_members */
2243 0, /* tp_getset */
2244 0, /* tp_base */
2245 0, /* tp_dict */
2246 0, /* tp_descr_get */
2247 0, /* tp_descr_set */
2248 0, /* tp_dictoffset */
2249 0, /* tp_init */
2250 PyType_GenericAlloc, /* tp_alloc */
2251 zip_new, /* tp_new */
2252 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002253};
Barry Warsawbd599b52000-08-03 15:45:29 +00002254
2255
Guido van Rossum79f25d91997-04-29 20:08:16 +00002256static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 {"__build_class__", (PyCFunction)builtin___build_class__,
2258 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2259 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2260 {"abs", builtin_abs, METH_O, abs_doc},
2261 {"all", builtin_all, METH_O, all_doc},
2262 {"any", builtin_any, METH_O, any_doc},
2263 {"ascii", builtin_ascii, METH_O, ascii_doc},
2264 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002265 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2267 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2268 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2269 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2270 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2271 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2272 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2273 {"format", builtin_format, METH_VARARGS, format_doc},
2274 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2275 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2276 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2277 {"hash", builtin_hash, METH_O, hash_doc},
2278 {"hex", builtin_hex, METH_O, hex_doc},
2279 {"id", builtin_id, METH_O, id_doc},
2280 {"input", builtin_input, METH_VARARGS, input_doc},
2281 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2282 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2283 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2284 {"len", builtin_len, METH_O, len_doc},
2285 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2286 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2287 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2288 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2289 {"oct", builtin_oct, METH_O, oct_doc},
2290 {"ord", builtin_ord, METH_O, ord_doc},
2291 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2292 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2293 {"repr", builtin_repr, METH_O, repr_doc},
2294 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2295 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2296 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2297 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2298 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2299 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002300};
2301
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002302PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002303"Built-in functions, exceptions, and other objects.\n\
2304\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002305Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002306
Martin v. Löwis1a214512008-06-11 05:26:20 +00002307static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 PyModuleDef_HEAD_INIT,
2309 "builtins",
2310 builtin_doc,
2311 -1, /* multiple "initialization" just copies the module dict. */
2312 builtin_methods,
2313 NULL,
2314 NULL,
2315 NULL,
2316 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002317};
2318
2319
Guido van Rossum25ce5661997-08-02 03:10:38 +00002320PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002321_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 PyObject *mod, *dict, *debug;
2324 mod = PyModule_Create(&builtinsmodule);
2325 if (mod == NULL)
2326 return NULL;
2327 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002328
Tim Peters7571a0f2003-03-23 17:52:28 +00002329#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 /* "builtins" exposes a number of statically allocated objects
2331 * that, before this code was added in 2.3, never showed up in
2332 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2333 * result, programs leaking references to None and False (etc)
2334 * couldn't be diagnosed by examining sys.getobjects(0).
2335 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002336#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2337#else
2338#define ADD_TO_ALL(OBJECT) (void)0
2339#endif
2340
Tim Peters4b7625e2001-09-13 21:37:17 +00002341#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2343 return NULL; \
2344 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 SETBUILTIN("None", Py_None);
2347 SETBUILTIN("Ellipsis", Py_Ellipsis);
2348 SETBUILTIN("NotImplemented", Py_NotImplemented);
2349 SETBUILTIN("False", Py_False);
2350 SETBUILTIN("True", Py_True);
2351 SETBUILTIN("bool", &PyBool_Type);
2352 SETBUILTIN("memoryview", &PyMemoryView_Type);
2353 SETBUILTIN("bytearray", &PyByteArray_Type);
2354 SETBUILTIN("bytes", &PyBytes_Type);
2355 SETBUILTIN("classmethod", &PyClassMethod_Type);
2356 SETBUILTIN("complex", &PyComplex_Type);
2357 SETBUILTIN("dict", &PyDict_Type);
2358 SETBUILTIN("enumerate", &PyEnum_Type);
2359 SETBUILTIN("filter", &PyFilter_Type);
2360 SETBUILTIN("float", &PyFloat_Type);
2361 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2362 SETBUILTIN("property", &PyProperty_Type);
2363 SETBUILTIN("int", &PyLong_Type);
2364 SETBUILTIN("list", &PyList_Type);
2365 SETBUILTIN("map", &PyMap_Type);
2366 SETBUILTIN("object", &PyBaseObject_Type);
2367 SETBUILTIN("range", &PyRange_Type);
2368 SETBUILTIN("reversed", &PyReversed_Type);
2369 SETBUILTIN("set", &PySet_Type);
2370 SETBUILTIN("slice", &PySlice_Type);
2371 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2372 SETBUILTIN("str", &PyUnicode_Type);
2373 SETBUILTIN("super", &PySuper_Type);
2374 SETBUILTIN("tuple", &PyTuple_Type);
2375 SETBUILTIN("type", &PyType_Type);
2376 SETBUILTIN("zip", &PyZip_Type);
2377 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2378 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2379 Py_XDECREF(debug);
2380 return NULL;
2381 }
2382 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002385#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002386#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002387}