blob: c6bb16c4e11dab6b6a5b542fe25e45eef8caed6b [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;
Brett Cannonb94767f2011-02-22 20:15:44 +000040 Py_ssize_t nargs;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 assert(args != NULL);
43 if (!PyTuple_Check(args)) {
44 PyErr_SetString(PyExc_TypeError,
45 "__build_class__: args is not a tuple");
46 return NULL;
47 }
48 nargs = PyTuple_GET_SIZE(args);
49 if (nargs < 2) {
50 PyErr_SetString(PyExc_TypeError,
51 "__build_class__: not enough arguments");
52 return NULL;
53 }
54 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
55 name = PyTuple_GET_ITEM(args, 1);
56 if (!PyUnicode_Check(name)) {
57 PyErr_SetString(PyExc_TypeError,
58 "__build_class__: name is not a string");
59 return NULL;
60 }
61 bases = PyTuple_GetSlice(args, 2, nargs);
62 if (bases == NULL)
63 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 if (kwds == NULL) {
66 meta = NULL;
67 mkw = NULL;
68 }
69 else {
70 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
71 if (mkw == NULL) {
72 Py_DECREF(bases);
73 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000074 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 meta = PyDict_GetItemString(mkw, "metaclass");
76 if (meta != NULL) {
77 Py_INCREF(meta);
78 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
79 Py_DECREF(meta);
80 Py_DECREF(mkw);
81 Py_DECREF(bases);
82 return NULL;
83 }
84 }
85 }
86 if (meta == NULL) {
87 if (PyTuple_GET_SIZE(bases) == 0)
88 meta = (PyObject *) (&PyType_Type);
89 else {
90 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
91 meta = (PyObject *) (base0->ob_type);
92 }
93 Py_INCREF(meta);
94 }
95 prep = PyObject_GetAttrString(meta, "__prepare__");
96 if (prep == NULL) {
97 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
98 PyErr_Clear();
99 ns = PyDict_New();
100 }
101 else {
102 Py_DECREF(meta);
103 Py_XDECREF(mkw);
104 Py_DECREF(bases);
105 return NULL;
106 }
107 }
108 else {
109 PyObject *pargs = PyTuple_Pack(2, name, bases);
110 if (pargs == NULL) {
111 Py_DECREF(prep);
112 Py_DECREF(meta);
113 Py_XDECREF(mkw);
114 Py_DECREF(bases);
115 return NULL;
116 }
117 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
118 Py_DECREF(pargs);
119 Py_DECREF(prep);
120 }
121 if (ns == NULL) {
122 Py_DECREF(meta);
123 Py_XDECREF(mkw);
124 Py_DECREF(bases);
125 return NULL;
126 }
127 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
128 if (cell != NULL) {
129 PyObject *margs;
130 margs = PyTuple_Pack(3, name, bases, ns);
131 if (margs != NULL) {
132 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
133 Py_DECREF(margs);
134 }
135 if (cls != NULL && PyCell_Check(cell)) {
136 Py_INCREF(cls);
137 PyCell_SET(cell, cls);
138 }
139 Py_DECREF(cell);
140 }
141 Py_DECREF(ns);
142 Py_DECREF(meta);
143 Py_XDECREF(mkw);
144 Py_DECREF(bases);
145 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000146}
147
148PyDoc_STRVAR(build_class_doc,
149"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
150\n\
151Internal helper function used by the class statement.");
152
153static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000154builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
157 "level", 0};
158 char *name;
159 PyObject *globals = NULL;
160 PyObject *locals = NULL;
161 PyObject *fromlist = NULL;
162 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
165 kwlist, &name, &globals, &locals, &fromlist, &level))
166 return NULL;
167 return PyImport_ImportModuleLevel(name, globals, locals,
168 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000169}
170
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000171PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000172"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000173\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000174Import a module. Because this function is meant for use by the Python\n\
175interpreter and not for general use it is better to use\n\
176importlib.import_module() to programmatically import a module.\n\
177\n\
178The globals argument is only used to determine the context;\n\
179they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000180should be a list of names to emulate ``from name import ...'', or an\n\
181empty list to emulate ``import name''.\n\
182When importing a module from a package, note that __import__('A.B', ...)\n\
183returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000184fromlist is not empty. Level is used to determine whether to perform \n\
185absolute or relative imports. -1 is the original strategy of attempting\n\
186both absolute and relative imports, 0 is absolute, a positive number\n\
187is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000188
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000189
Guido van Rossum79f25d91997-04-29 20:08:16 +0000190static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000191builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000194}
195
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000196PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000197"abs(number) -> number\n\
198\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000199Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000200
Raymond Hettinger96229b12005-03-11 06:49:40 +0000201static PyObject *
202builtin_all(PyObject *self, PyObject *v)
203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 PyObject *it, *item;
205 PyObject *(*iternext)(PyObject *);
206 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 it = PyObject_GetIter(v);
209 if (it == NULL)
210 return NULL;
211 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 for (;;) {
214 item = iternext(it);
215 if (item == NULL)
216 break;
217 cmp = PyObject_IsTrue(item);
218 Py_DECREF(item);
219 if (cmp < 0) {
220 Py_DECREF(it);
221 return NULL;
222 }
223 if (cmp == 0) {
224 Py_DECREF(it);
225 Py_RETURN_FALSE;
226 }
227 }
228 Py_DECREF(it);
229 if (PyErr_Occurred()) {
230 if (PyErr_ExceptionMatches(PyExc_StopIteration))
231 PyErr_Clear();
232 else
233 return NULL;
234 }
235 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000236}
237
238PyDoc_STRVAR(all_doc,
239"all(iterable) -> bool\n\
240\n\
241Return True if bool(x) is True for all values x in the iterable.");
242
243static PyObject *
244builtin_any(PyObject *self, PyObject *v)
245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 PyObject *it, *item;
247 PyObject *(*iternext)(PyObject *);
248 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 it = PyObject_GetIter(v);
251 if (it == NULL)
252 return NULL;
253 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 for (;;) {
256 item = iternext(it);
257 if (item == NULL)
258 break;
259 cmp = PyObject_IsTrue(item);
260 Py_DECREF(item);
261 if (cmp < 0) {
262 Py_DECREF(it);
263 return NULL;
264 }
265 if (cmp == 1) {
266 Py_DECREF(it);
267 Py_RETURN_TRUE;
268 }
269 }
270 Py_DECREF(it);
271 if (PyErr_Occurred()) {
272 if (PyErr_ExceptionMatches(PyExc_StopIteration))
273 PyErr_Clear();
274 else
275 return NULL;
276 }
277 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000278}
279
280PyDoc_STRVAR(any_doc,
281"any(iterable) -> bool\n\
282\n\
283Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000284
Georg Brandl559e5d72008-06-11 18:37:52 +0000285static PyObject *
286builtin_ascii(PyObject *self, PyObject *v)
287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000289}
290
291PyDoc_STRVAR(ascii_doc,
292"ascii(object) -> string\n\
293\n\
294As repr(), return a string containing a printable representation of an\n\
295object, but escape the non-ASCII characters in the string returned by\n\
296repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
297to that returned by repr() in Python 2.");
298
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000299
Guido van Rossum79f25d91997-04-29 20:08:16 +0000300static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000301builtin_bin(PyObject *self, PyObject *v)
302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000304}
305
306PyDoc_STRVAR(bin_doc,
307"bin(number) -> string\n\
308\n\
309Return the binary representation of an integer or long integer.");
310
311
Antoine Pitroue71362d2010-11-27 22:00:11 +0000312static PyObject *
313builtin_callable(PyObject *self, PyObject *v)
314{
315 return PyBool_FromLong((long)PyCallable_Check(v));
316}
317
318PyDoc_STRVAR(callable_doc,
319"callable(object) -> bool\n\
320\n\
321Return whether the object is callable (i.e., some kind of function).\n\
322Note that classes are callable, as are instances of classes with a\n\
323__call__() method.");
324
325
Raymond Hettinger17301e92008-03-13 00:19:26 +0000326typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 PyObject_HEAD
328 PyObject *func;
329 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000330} filterobject;
331
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000332static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000333filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 PyObject *func, *seq;
336 PyObject *it;
337 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
340 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
343 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 /* Get iterator. */
346 it = PyObject_GetIter(seq);
347 if (it == NULL)
348 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 /* create filterobject structure */
351 lz = (filterobject *)type->tp_alloc(type, 0);
352 if (lz == NULL) {
353 Py_DECREF(it);
354 return NULL;
355 }
356 Py_INCREF(func);
357 lz->func = func;
358 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000361}
362
363static void
364filter_dealloc(filterobject *lz)
365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 PyObject_GC_UnTrack(lz);
367 Py_XDECREF(lz->func);
368 Py_XDECREF(lz->it);
369 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000370}
371
372static int
373filter_traverse(filterobject *lz, visitproc visit, void *arg)
374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 Py_VISIT(lz->it);
376 Py_VISIT(lz->func);
377 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000378}
379
380static PyObject *
381filter_next(filterobject *lz)
382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 PyObject *item;
384 PyObject *it = lz->it;
385 long ok;
386 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 iternext = *Py_TYPE(it)->tp_iternext;
389 for (;;) {
390 item = iternext(it);
391 if (item == NULL)
392 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
395 ok = PyObject_IsTrue(item);
396 } else {
397 PyObject *good;
398 good = PyObject_CallFunctionObjArgs(lz->func,
399 item, NULL);
400 if (good == NULL) {
401 Py_DECREF(item);
402 return NULL;
403 }
404 ok = PyObject_IsTrue(good);
405 Py_DECREF(good);
406 }
407 if (ok)
408 return item;
409 Py_DECREF(item);
410 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000411}
412
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000413PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000414"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000415\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000416Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000417is true. If function is None, return the items that are true.");
418
419PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 PyVarObject_HEAD_INIT(&PyType_Type, 0)
421 "filter", /* tp_name */
422 sizeof(filterobject), /* tp_basicsize */
423 0, /* tp_itemsize */
424 /* methods */
425 (destructor)filter_dealloc, /* tp_dealloc */
426 0, /* tp_print */
427 0, /* tp_getattr */
428 0, /* tp_setattr */
429 0, /* tp_reserved */
430 0, /* tp_repr */
431 0, /* tp_as_number */
432 0, /* tp_as_sequence */
433 0, /* tp_as_mapping */
434 0, /* tp_hash */
435 0, /* tp_call */
436 0, /* tp_str */
437 PyObject_GenericGetAttr, /* tp_getattro */
438 0, /* tp_setattro */
439 0, /* tp_as_buffer */
440 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
441 Py_TPFLAGS_BASETYPE, /* tp_flags */
442 filter_doc, /* tp_doc */
443 (traverseproc)filter_traverse, /* tp_traverse */
444 0, /* tp_clear */
445 0, /* tp_richcompare */
446 0, /* tp_weaklistoffset */
447 PyObject_SelfIter, /* tp_iter */
448 (iternextfunc)filter_next, /* tp_iternext */
449 0, /* tp_methods */
450 0, /* tp_members */
451 0, /* tp_getset */
452 0, /* tp_base */
453 0, /* tp_dict */
454 0, /* tp_descr_get */
455 0, /* tp_descr_set */
456 0, /* tp_dictoffset */
457 0, /* tp_init */
458 PyType_GenericAlloc, /* tp_alloc */
459 filter_new, /* tp_new */
460 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000461};
462
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000463
Eric Smith8c663262007-08-25 02:26:07 +0000464static PyObject *
465builtin_format(PyObject *self, PyObject *args)
466{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000467 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000468 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000469
Eric Smith8fd3eba2008-02-17 19:48:00 +0000470 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000472
Eric Smith8fd3eba2008-02-17 19:48:00 +0000473 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000474}
475
Eric Smith8c663262007-08-25 02:26:07 +0000476PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000477"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000478\n\
Eric Smith81936692007-08-31 01:14:01 +0000479Returns value.__format__(format_spec)\n\
480format_spec defaults to \"\"");
481
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000482static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000483builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 if (!PyArg_ParseTuple(args, "i:chr", &x))
488 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000491}
492
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000493PyDoc_VAR(chr_doc) = PyDoc_STR(
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000494"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000495\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000496Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000497)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000498#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000499PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000500"\nIf 0x10000 <= i, a surrogate pair is returned."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000501)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000502#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000503;
Guido van Rossum09095f32000-03-10 23:00:52 +0000504
505
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000506static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000507source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 char *str;
510 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 if (PyUnicode_Check(cmd)) {
513 cf->cf_flags |= PyCF_IGNORE_COOKIE;
514 cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL);
515 if (cmd == NULL)
516 return NULL;
517 }
518 else if (!PyObject_CheckReadBuffer(cmd)) {
519 PyErr_Format(PyExc_TypeError,
520 "%s() arg 1 must be a %s object",
521 funcname, what);
522 return NULL;
523 }
524 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
525 return NULL;
526 }
527 if (strlen(str) != size) {
528 PyErr_SetString(PyExc_TypeError,
529 "source code string cannot contain null bytes");
530 return NULL;
531 }
532 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000533}
534
Guido van Rossum79f25d91997-04-29 20:08:16 +0000535static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000536builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 char *str;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000539 PyObject *filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 char *filename;
541 char *startstr;
542 int mode = -1;
543 int dont_inherit = 0;
544 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000545 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 int is_ast;
547 PyCompilerFlags cf;
548 PyObject *cmd;
549 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000550 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000552 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000553
Georg Brandl8334fd92010-12-04 10:26:46 +0000554 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000555 &cmd,
556 PyUnicode_FSConverter, &filename_obj,
557 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000558 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000560
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000561 filename = PyBytes_AS_STRING(filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 if (supplied_flags &
565 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
566 {
567 PyErr_SetString(PyExc_ValueError,
568 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000569 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 }
571 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000572
Georg Brandl8334fd92010-12-04 10:26:46 +0000573 if (optimize < -1 || optimize > 2) {
574 PyErr_SetString(PyExc_ValueError,
575 "compile(): invalid optimize value");
576 goto error;
577 }
578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 if (!dont_inherit) {
580 PyEval_MergeCompilerFlags(&cf);
581 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 if (strcmp(startstr, "exec") == 0)
584 mode = 0;
585 else if (strcmp(startstr, "eval") == 0)
586 mode = 1;
587 else if (strcmp(startstr, "single") == 0)
588 mode = 2;
589 else {
590 PyErr_SetString(PyExc_ValueError,
591 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000592 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 is_ast = PyAST_Check(cmd);
596 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000597 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 if (supplied_flags & PyCF_ONLY_AST) {
600 Py_INCREF(cmd);
601 result = cmd;
602 }
603 else {
604 PyArena *arena;
605 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 arena = PyArena_New();
608 mod = PyAST_obj2mod(cmd, arena, mode);
609 if (mod == NULL) {
610 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000611 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 }
Georg Brandl8334fd92010-12-04 10:26:46 +0000613 result = (PyObject*)PyAST_CompileEx(mod, filename,
614 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 PyArena_Free(arena);
616 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000617 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
621 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000622 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000623
Georg Brandl8334fd92010-12-04 10:26:46 +0000624 result = Py_CompileStringExFlags(str, filename, start[mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000625 goto finally;
626
627error:
628 result = NULL;
629finally:
630 Py_DECREF(filename_obj);
631 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000632}
633
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000634PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000635"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000636\n\
637Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000638into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000639The filename will be used for run-time error messages.\n\
640The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000641single (interactive) statement, or 'eval' to compile an expression.\n\
642The flags argument, if present, controls which future statements influence\n\
643the compilation of the code.\n\
644The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
645the effects of any future statements in effect in the code calling\n\
646compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000647in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000648
Guido van Rossum79f25d91997-04-29 20:08:16 +0000649static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000650builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
655 return NULL;
656 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000657}
658
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000659PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000660"dir([object]) -> list of strings\n"
661"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000662"If called without an argument, return the names in the current scope.\n"
663"Else, return an alphabetized list of names comprising (some of) the attributes\n"
664"of the given object, and of attributes reachable from it.\n"
665"If the object supplies a method named __dir__, it will be used; otherwise\n"
666"the default dir() logic is used and returns:\n"
667" for a module object: the module's attributes.\n"
668" for a class object: its attributes, and recursively the attributes\n"
669" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000670" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000671" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000672
Guido van Rossum79f25d91997-04-29 20:08:16 +0000673static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000674builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
679 return NULL;
680 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000681}
682
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000683PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000684"divmod(x, y) -> (div, mod)\n\
685\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000686Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000687
688
Guido van Rossum79f25d91997-04-29 20:08:16 +0000689static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000690builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 PyObject *cmd, *result, *tmp = NULL;
693 PyObject *globals = Py_None, *locals = Py_None;
694 char *str;
695 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
698 return NULL;
699 if (locals != Py_None && !PyMapping_Check(locals)) {
700 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
701 return NULL;
702 }
703 if (globals != Py_None && !PyDict_Check(globals)) {
704 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
705 "globals must be a real dict; try eval(expr, {}, mapping)"
706 : "globals must be a dict");
707 return NULL;
708 }
709 if (globals == Py_None) {
710 globals = PyEval_GetGlobals();
711 if (locals == Py_None)
712 locals = PyEval_GetLocals();
713 }
714 else if (locals == Py_None)
715 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 if (globals == NULL || locals == NULL) {
718 PyErr_SetString(PyExc_TypeError,
719 "eval must be given globals and locals "
720 "when called without a frame");
721 return NULL;
722 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
725 if (PyDict_SetItemString(globals, "__builtins__",
726 PyEval_GetBuiltins()) != 0)
727 return NULL;
728 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 if (PyCode_Check(cmd)) {
731 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
732 PyErr_SetString(PyExc_TypeError,
733 "code object passed to eval() may not contain free variables");
734 return NULL;
735 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000736 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
740 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
741 if (str == NULL)
742 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 while (*str == ' ' || *str == '\t')
745 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 (void)PyEval_MergeCompilerFlags(&cf);
748 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
749 Py_XDECREF(tmp);
750 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000751}
752
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000753PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000754"eval(source[, globals[, locals]]) -> value\n\
755\n\
756Evaluate the source in the context of globals and locals.\n\
757The source may be a string representing a Python expression\n\
758or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000759The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000760defaulting to the current globals and locals.\n\
761If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000762
Georg Brandl7cae87c2006-09-06 06:51:57 +0000763static PyObject *
764builtin_exec(PyObject *self, PyObject *args)
765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 PyObject *v;
767 PyObject *prog, *globals = Py_None, *locals = Py_None;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
770 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 if (globals == Py_None) {
773 globals = PyEval_GetGlobals();
774 if (locals == Py_None) {
775 locals = PyEval_GetLocals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 }
777 if (!globals || !locals) {
778 PyErr_SetString(PyExc_SystemError,
779 "globals and locals cannot be NULL");
780 return NULL;
781 }
782 }
783 else if (locals == Py_None)
784 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 if (!PyDict_Check(globals)) {
787 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
788 globals->ob_type->tp_name);
789 return NULL;
790 }
791 if (!PyMapping_Check(locals)) {
792 PyErr_Format(PyExc_TypeError,
793 "arg 3 must be a mapping or None, not %.100s",
794 locals->ob_type->tp_name);
795 return NULL;
796 }
797 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
798 if (PyDict_SetItemString(globals, "__builtins__",
799 PyEval_GetBuiltins()) != 0)
800 return NULL;
801 }
802
803 if (PyCode_Check(prog)) {
804 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
805 PyErr_SetString(PyExc_TypeError,
806 "code object passed to exec() may not "
807 "contain free variables");
808 return NULL;
809 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000810 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 }
812 else {
813 char *str;
814 PyCompilerFlags cf;
815 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
816 str = source_as_string(prog, "exec",
817 "string, bytes or code", &cf);
818 if (str == NULL)
819 return NULL;
820 if (PyEval_MergeCompilerFlags(&cf))
821 v = PyRun_StringFlags(str, Py_file_input, globals,
822 locals, &cf);
823 else
824 v = PyRun_String(str, Py_file_input, globals, locals);
825 }
826 if (v == NULL)
827 return NULL;
828 Py_DECREF(v);
829 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000830}
831
832PyDoc_STRVAR(exec_doc,
833"exec(object[, globals[, locals]])\n\
834\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000835Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000836object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000837The globals and locals are dictionaries, defaulting to the current\n\
838globals and locals. If only globals is given, locals defaults to it.");
839
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000840
Guido van Rossum79f25d91997-04-29 20:08:16 +0000841static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000842builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 PyObject *v, *result, *dflt = NULL;
845 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
848 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 if (!PyUnicode_Check(name)) {
851 PyErr_SetString(PyExc_TypeError,
852 "getattr(): attribute name must be string");
853 return NULL;
854 }
855 result = PyObject_GetAttr(v, name);
856 if (result == NULL && dflt != NULL &&
857 PyErr_ExceptionMatches(PyExc_AttributeError))
858 {
859 PyErr_Clear();
860 Py_INCREF(dflt);
861 result = dflt;
862 }
863 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000864}
865
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000866PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000867"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000868\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000869Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
870When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000871exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000872
873
Guido van Rossum79f25d91997-04-29 20:08:16 +0000874static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000875builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 d = PyEval_GetGlobals();
880 Py_XINCREF(d);
881 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000882}
883
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000884PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000885"globals() -> dictionary\n\
886\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000887Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000888
889
Guido van Rossum79f25d91997-04-29 20:08:16 +0000890static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000891builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 PyObject *v;
894 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
897 return NULL;
898 if (!PyUnicode_Check(name)) {
899 PyErr_SetString(PyExc_TypeError,
900 "hasattr(): attribute name must be string");
901 return NULL;
902 }
903 v = PyObject_GetAttr(v, name);
904 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000905 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000907 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000909 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 }
911 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000912 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000913}
914
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000915PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000916"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000917\n\
918Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000919(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000920
921
Guido van Rossum79f25d91997-04-29 20:08:16 +0000922static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000923builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000926}
927
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000928PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000929"id(object) -> integer\n\
930\n\
931Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000932simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000933
934
Raymond Hettingera6c60372008-03-13 01:26:19 +0000935/* map object ************************************************************/
936
937typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 PyObject_HEAD
939 PyObject *iters;
940 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000941} mapobject;
942
Guido van Rossum79f25d91997-04-29 20:08:16 +0000943static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000944map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 PyObject *it, *iters, *func;
947 mapobject *lz;
948 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
951 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 numargs = PyTuple_Size(args);
954 if (numargs < 2) {
955 PyErr_SetString(PyExc_TypeError,
956 "map() must have at least two arguments.");
957 return NULL;
958 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 iters = PyTuple_New(numargs-1);
961 if (iters == NULL)
962 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 for (i=1 ; i<numargs ; i++) {
965 /* Get iterator. */
966 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
967 if (it == NULL) {
968 Py_DECREF(iters);
969 return NULL;
970 }
971 PyTuple_SET_ITEM(iters, i-1, it);
972 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 /* create mapobject structure */
975 lz = (mapobject *)type->tp_alloc(type, 0);
976 if (lz == NULL) {
977 Py_DECREF(iters);
978 return NULL;
979 }
980 lz->iters = iters;
981 func = PyTuple_GET_ITEM(args, 0);
982 Py_INCREF(func);
983 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000986}
987
988static void
989map_dealloc(mapobject *lz)
990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 PyObject_GC_UnTrack(lz);
992 Py_XDECREF(lz->iters);
993 Py_XDECREF(lz->func);
994 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +0000995}
996
997static int
998map_traverse(mapobject *lz, visitproc visit, void *arg)
999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 Py_VISIT(lz->iters);
1001 Py_VISIT(lz->func);
1002 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001003}
1004
1005static PyObject *
1006map_next(mapobject *lz)
1007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 PyObject *val;
1009 PyObject *argtuple;
1010 PyObject *result;
1011 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 numargs = PyTuple_Size(lz->iters);
1014 argtuple = PyTuple_New(numargs);
1015 if (argtuple == NULL)
1016 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 for (i=0 ; i<numargs ; i++) {
1019 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1020 if (val == NULL) {
1021 Py_DECREF(argtuple);
1022 return NULL;
1023 }
1024 PyTuple_SET_ITEM(argtuple, i, val);
1025 }
1026 result = PyObject_Call(lz->func, argtuple, NULL);
1027 Py_DECREF(argtuple);
1028 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001029}
1030
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001031PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001032"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001033\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001034Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001036
Raymond Hettingera6c60372008-03-13 01:26:19 +00001037PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1039 "map", /* tp_name */
1040 sizeof(mapobject), /* tp_basicsize */
1041 0, /* tp_itemsize */
1042 /* methods */
1043 (destructor)map_dealloc, /* tp_dealloc */
1044 0, /* tp_print */
1045 0, /* tp_getattr */
1046 0, /* tp_setattr */
1047 0, /* tp_reserved */
1048 0, /* tp_repr */
1049 0, /* tp_as_number */
1050 0, /* tp_as_sequence */
1051 0, /* tp_as_mapping */
1052 0, /* tp_hash */
1053 0, /* tp_call */
1054 0, /* tp_str */
1055 PyObject_GenericGetAttr, /* tp_getattro */
1056 0, /* tp_setattro */
1057 0, /* tp_as_buffer */
1058 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1059 Py_TPFLAGS_BASETYPE, /* tp_flags */
1060 map_doc, /* tp_doc */
1061 (traverseproc)map_traverse, /* tp_traverse */
1062 0, /* tp_clear */
1063 0, /* tp_richcompare */
1064 0, /* tp_weaklistoffset */
1065 PyObject_SelfIter, /* tp_iter */
1066 (iternextfunc)map_next, /* tp_iternext */
1067 0, /* tp_methods */
1068 0, /* tp_members */
1069 0, /* tp_getset */
1070 0, /* tp_base */
1071 0, /* tp_dict */
1072 0, /* tp_descr_get */
1073 0, /* tp_descr_set */
1074 0, /* tp_dictoffset */
1075 0, /* tp_init */
1076 PyType_GenericAlloc, /* tp_alloc */
1077 map_new, /* tp_new */
1078 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001079};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001080
Guido van Rossum79f25d91997-04-29 20:08:16 +00001081static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001082builtin_next(PyObject *self, PyObject *args)
1083{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 PyObject *it, *res;
1085 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1088 return NULL;
1089 if (!PyIter_Check(it)) {
1090 PyErr_Format(PyExc_TypeError,
1091 "%.200s object is not an iterator",
1092 it->ob_type->tp_name);
1093 return NULL;
1094 }
1095
1096 res = (*it->ob_type->tp_iternext)(it);
1097 if (res != NULL) {
1098 return res;
1099 } else if (def != NULL) {
1100 if (PyErr_Occurred()) {
1101 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1102 return NULL;
1103 PyErr_Clear();
1104 }
1105 Py_INCREF(def);
1106 return def;
1107 } else if (PyErr_Occurred()) {
1108 return NULL;
1109 } else {
1110 PyErr_SetNone(PyExc_StopIteration);
1111 return NULL;
1112 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001113}
1114
1115PyDoc_STRVAR(next_doc,
1116"next(iterator[, default])\n\
1117\n\
1118Return the next item from the iterator. If default is given and the iterator\n\
1119is exhausted, it is returned instead of raising StopIteration.");
1120
1121
1122static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001123builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 PyObject *v;
1126 PyObject *name;
1127 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1130 return NULL;
1131 if (PyObject_SetAttr(v, name, value) != 0)
1132 return NULL;
1133 Py_INCREF(Py_None);
1134 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001135}
1136
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001137PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001138"setattr(object, name, value)\n\
1139\n\
1140Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001141``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001142
1143
Guido van Rossum79f25d91997-04-29 20:08:16 +00001144static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001145builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 PyObject *v;
1148 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1151 return NULL;
1152 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1153 return NULL;
1154 Py_INCREF(Py_None);
1155 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001156}
1157
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001158PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001159"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001160\n\
1161Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001162``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001163
1164
Guido van Rossum79f25d91997-04-29 20:08:16 +00001165static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001166builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001167{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001168 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 x = PyObject_Hash(v);
1171 if (x == -1)
1172 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001173 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001174}
1175
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001176PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001177"hash(object) -> integer\n\
1178\n\
1179Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001180the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001181
1182
Guido van Rossum79f25d91997-04-29 20:08:16 +00001183static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001184builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001187}
1188
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001189PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001190"hex(number) -> string\n\
1191\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001192Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001193
1194
Guido van Rossum79f25d91997-04-29 20:08:16 +00001195static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001196builtin_iter(PyObject *self, PyObject *args)
1197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1201 return NULL;
1202 if (w == NULL)
1203 return PyObject_GetIter(v);
1204 if (!PyCallable_Check(v)) {
1205 PyErr_SetString(PyExc_TypeError,
1206 "iter(v, w): v must be callable");
1207 return NULL;
1208 }
1209 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001210}
1211
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001212PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001213"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001214iter(callable, sentinel) -> iterator\n\
1215\n\
1216Get an iterator from an object. In the first form, the argument must\n\
1217supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001218In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001219
1220
1221static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001222builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 res = PyObject_Size(v);
1227 if (res < 0 && PyErr_Occurred())
1228 return NULL;
1229 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001230}
1231
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001232PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001233"len(object) -> integer\n\
1234\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001235Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001236
1237
Guido van Rossum79f25d91997-04-29 20:08:16 +00001238static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001239builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 d = PyEval_GetLocals();
1244 Py_XINCREF(d);
1245 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001246}
1247
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001248PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001249"locals() -> dictionary\n\
1250\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001251Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001252
1253
Guido van Rossum79f25d91997-04-29 20:08:16 +00001254static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001255min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1258 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 if (PyTuple_Size(args) > 1)
1261 v = args;
1262 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1263 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1266 keyfunc = PyDict_GetItemString(kwds, "key");
1267 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1268 PyErr_Format(PyExc_TypeError,
1269 "%s() got an unexpected keyword argument", name);
1270 return NULL;
1271 }
1272 Py_INCREF(keyfunc);
1273 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 it = PyObject_GetIter(v);
1276 if (it == NULL) {
1277 Py_XDECREF(keyfunc);
1278 return NULL;
1279 }
Tim Petersc3074532001-05-03 07:00:32 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 maxitem = NULL; /* the result */
1282 maxval = NULL; /* the value associated with the result */
1283 while (( item = PyIter_Next(it) )) {
1284 /* get the value from the key function */
1285 if (keyfunc != NULL) {
1286 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1287 if (val == NULL)
1288 goto Fail_it_item;
1289 }
1290 /* no key function; the value is the item */
1291 else {
1292 val = item;
1293 Py_INCREF(val);
1294 }
Tim Petersc3074532001-05-03 07:00:32 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 /* maximum value and item are unset; set them */
1297 if (maxval == NULL) {
1298 maxitem = item;
1299 maxval = val;
1300 }
1301 /* maximum value and item are set; update them as necessary */
1302 else {
1303 int cmp = PyObject_RichCompareBool(val, maxval, op);
1304 if (cmp < 0)
1305 goto Fail_it_item_and_val;
1306 else if (cmp > 0) {
1307 Py_DECREF(maxval);
1308 Py_DECREF(maxitem);
1309 maxval = val;
1310 maxitem = item;
1311 }
1312 else {
1313 Py_DECREF(item);
1314 Py_DECREF(val);
1315 }
1316 }
1317 }
1318 if (PyErr_Occurred())
1319 goto Fail_it;
1320 if (maxval == NULL) {
1321 PyErr_Format(PyExc_ValueError,
1322 "%s() arg is an empty sequence", name);
1323 assert(maxitem == NULL);
1324 }
1325 else
1326 Py_DECREF(maxval);
1327 Py_DECREF(it);
1328 Py_XDECREF(keyfunc);
1329 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001330
1331Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001333Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001335Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 Py_XDECREF(maxval);
1337 Py_XDECREF(maxitem);
1338 Py_DECREF(it);
1339 Py_XDECREF(keyfunc);
1340 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001341}
1342
Guido van Rossum79f25d91997-04-29 20:08:16 +00001343static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001344builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001347}
1348
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001349PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001350"min(iterable[, key=func]) -> value\n\
1351min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001352\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001353With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001354With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001355
1356
Guido van Rossum79f25d91997-04-29 20:08:16 +00001357static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001358builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001361}
1362
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001363PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001364"max(iterable[, key=func]) -> value\n\
1365max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001366\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001367With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001368With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001369
1370
Guido van Rossum79f25d91997-04-29 20:08:16 +00001371static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001372builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001375}
1376
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001377PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001378"oct(number) -> string\n\
1379\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001380Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001381
1382
Guido van Rossum79f25d91997-04-29 20:08:16 +00001383static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001384builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 long ord;
1387 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 if (PyBytes_Check(obj)) {
1390 size = PyBytes_GET_SIZE(obj);
1391 if (size == 1) {
1392 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1393 return PyLong_FromLong(ord);
1394 }
1395 }
1396 else if (PyUnicode_Check(obj)) {
1397 size = PyUnicode_GET_SIZE(obj);
1398 if (size == 1) {
1399 ord = (long)*PyUnicode_AS_UNICODE(obj);
1400 return PyLong_FromLong(ord);
1401 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001402#ifndef Py_UNICODE_WIDE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 if (size == 2) {
1404 /* Decode a valid surrogate pair */
1405 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1406 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1407 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1408 0xDC00 <= c1 && c1 <= 0xDFFF) {
1409 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1410 0x00010000);
1411 return PyLong_FromLong(ord);
1412 }
1413 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001414#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 }
1416 else if (PyByteArray_Check(obj)) {
1417 /* XXX Hopefully this is temporary */
1418 size = PyByteArray_GET_SIZE(obj);
1419 if (size == 1) {
1420 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1421 return PyLong_FromLong(ord);
1422 }
1423 }
1424 else {
1425 PyErr_Format(PyExc_TypeError,
1426 "ord() expected string of length 1, but " \
1427 "%.200s found", obj->ob_type->tp_name);
1428 return NULL;
1429 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 PyErr_Format(PyExc_TypeError,
1432 "ord() expected a character, "
1433 "but string of length %zd found",
1434 size);
1435 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001436}
1437
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001438PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001439"ord(c) -> integer\n\
1440\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001441Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001442)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001443#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001444PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001445"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001446)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001447#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001448;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001449
1450
Guido van Rossum79f25d91997-04-29 20:08:16 +00001451static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001452builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1457 return NULL;
1458 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001459}
1460
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001461PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001462"pow(x, y[, z]) -> number\n\
1463\n\
1464With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001465equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001466
1467
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001468
Guido van Rossum34343512006-11-30 22:13:52 +00001469static PyObject *
1470builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 static char *kwlist[] = {"sep", "end", "file", 0};
1473 static PyObject *dummy_args;
1474 PyObject *sep = NULL, *end = NULL, *file = NULL;
1475 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 if (dummy_args == NULL) {
1478 if (!(dummy_args = PyTuple_New(0)))
1479 return NULL;
1480 }
1481 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1482 kwlist, &sep, &end, &file))
1483 return NULL;
1484 if (file == NULL || file == Py_None) {
1485 file = PySys_GetObject("stdout");
1486 /* sys.stdout may be None when FILE* stdout isn't connected */
1487 if (file == Py_None)
1488 Py_RETURN_NONE;
1489 }
Guido van Rossum34343512006-11-30 22:13:52 +00001490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 if (sep == Py_None) {
1492 sep = NULL;
1493 }
1494 else if (sep && !PyUnicode_Check(sep)) {
1495 PyErr_Format(PyExc_TypeError,
1496 "sep must be None or a string, not %.200s",
1497 sep->ob_type->tp_name);
1498 return NULL;
1499 }
1500 if (end == Py_None) {
1501 end = NULL;
1502 }
1503 else if (end && !PyUnicode_Check(end)) {
1504 PyErr_Format(PyExc_TypeError,
1505 "end must be None or a string, not %.200s",
1506 end->ob_type->tp_name);
1507 return NULL;
1508 }
Guido van Rossum34343512006-11-30 22:13:52 +00001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 for (i = 0; i < PyTuple_Size(args); i++) {
1511 if (i > 0) {
1512 if (sep == NULL)
1513 err = PyFile_WriteString(" ", file);
1514 else
1515 err = PyFile_WriteObject(sep, file,
1516 Py_PRINT_RAW);
1517 if (err)
1518 return NULL;
1519 }
1520 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1521 Py_PRINT_RAW);
1522 if (err)
1523 return NULL;
1524 }
Guido van Rossum34343512006-11-30 22:13:52 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 if (end == NULL)
1527 err = PyFile_WriteString("\n", file);
1528 else
1529 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1530 if (err)
1531 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001534}
1535
1536PyDoc_STRVAR(print_doc,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001537"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001538\n\
1539Prints the values to a stream, or to sys.stdout by default.\n\
1540Optional keyword arguments:\n\
1541file: a file-like object (stream); defaults to the current sys.stdout.\n\
1542sep: string inserted between values, default a space.\n\
1543end: string appended after the last value, default a newline.");
1544
1545
Guido van Rossuma88a0332007-02-26 16:59:55 +00001546static PyObject *
1547builtin_input(PyObject *self, PyObject *args)
1548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 PyObject *promptarg = NULL;
1550 PyObject *fin = PySys_GetObject("stdin");
1551 PyObject *fout = PySys_GetObject("stdout");
1552 PyObject *ferr = PySys_GetObject("stderr");
1553 PyObject *tmp;
1554 long fd;
1555 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 /* Parse arguments */
1558 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1559 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 /* Check that stdin/out/err are intact */
1562 if (fin == NULL || fin == Py_None) {
1563 PyErr_SetString(PyExc_RuntimeError,
1564 "input(): lost sys.stdin");
1565 return NULL;
1566 }
1567 if (fout == NULL || fout == Py_None) {
1568 PyErr_SetString(PyExc_RuntimeError,
1569 "input(): lost sys.stdout");
1570 return NULL;
1571 }
1572 if (ferr == NULL || ferr == Py_None) {
1573 PyErr_SetString(PyExc_RuntimeError,
1574 "input(): lost sys.stderr");
1575 return NULL;
1576 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 /* First of all, flush stderr */
1579 tmp = PyObject_CallMethod(ferr, "flush", "");
1580 if (tmp == NULL)
1581 PyErr_Clear();
1582 else
1583 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 /* We should only use (GNU) readline if Python's sys.stdin and
1586 sys.stdout are the same as C's stdin and stdout, because we
1587 need to pass it those. */
1588 tmp = PyObject_CallMethod(fin, "fileno", "");
1589 if (tmp == NULL) {
1590 PyErr_Clear();
1591 tty = 0;
1592 }
1593 else {
1594 fd = PyLong_AsLong(tmp);
1595 Py_DECREF(tmp);
1596 if (fd < 0 && PyErr_Occurred())
1597 return NULL;
1598 tty = fd == fileno(stdin) && isatty(fd);
1599 }
1600 if (tty) {
1601 tmp = PyObject_CallMethod(fout, "fileno", "");
1602 if (tmp == NULL)
1603 PyErr_Clear();
1604 else {
1605 fd = PyLong_AsLong(tmp);
1606 Py_DECREF(tmp);
1607 if (fd < 0 && PyErr_Occurred())
1608 return NULL;
1609 tty = fd == fileno(stdout) && isatty(fd);
1610 }
1611 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 /* If we're interactive, use (GNU) readline */
1614 if (tty) {
1615 PyObject *po;
1616 char *prompt;
1617 char *s;
1618 PyObject *stdin_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001619 char *stdin_encoding_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001621 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1624 if (!stdin_encoding)
1625 /* stdin is a text stream, so it must have an
1626 encoding. */
1627 return NULL;
Victor Stinner306f0102010-05-19 01:06:22 +00001628 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
1629 if (stdin_encoding_str == NULL) {
1630 Py_DECREF(stdin_encoding);
1631 return NULL;
1632 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 tmp = PyObject_CallMethod(fout, "flush", "");
1634 if (tmp == NULL)
1635 PyErr_Clear();
1636 else
1637 Py_DECREF(tmp);
1638 if (promptarg != NULL) {
1639 PyObject *stringpo;
1640 PyObject *stdout_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001641 char *stdout_encoding_str;
1642 stdout_encoding = PyObject_GetAttrString(fout, "encoding");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 if (stdout_encoding == NULL) {
1644 Py_DECREF(stdin_encoding);
1645 return NULL;
1646 }
Victor Stinner306f0102010-05-19 01:06:22 +00001647 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
1648 if (stdout_encoding_str == NULL) {
1649 Py_DECREF(stdin_encoding);
1650 Py_DECREF(stdout_encoding);
1651 return NULL;
1652 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 stringpo = PyObject_Str(promptarg);
1654 if (stringpo == NULL) {
1655 Py_DECREF(stdin_encoding);
1656 Py_DECREF(stdout_encoding);
1657 return NULL;
1658 }
1659 po = PyUnicode_AsEncodedString(stringpo,
Victor Stinner306f0102010-05-19 01:06:22 +00001660 stdout_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 Py_DECREF(stdout_encoding);
1662 Py_DECREF(stringpo);
1663 if (po == NULL) {
1664 Py_DECREF(stdin_encoding);
1665 return NULL;
1666 }
1667 prompt = PyBytes_AsString(po);
1668 if (prompt == NULL) {
1669 Py_DECREF(stdin_encoding);
1670 Py_DECREF(po);
1671 return NULL;
1672 }
1673 }
1674 else {
1675 po = NULL;
1676 prompt = "";
1677 }
1678 s = PyOS_Readline(stdin, stdout, prompt);
1679 Py_XDECREF(po);
1680 if (s == NULL) {
1681 if (!PyErr_Occurred())
1682 PyErr_SetNone(PyExc_KeyboardInterrupt);
1683 Py_DECREF(stdin_encoding);
1684 return NULL;
1685 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001686
1687 len = strlen(s);
1688 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 PyErr_SetNone(PyExc_EOFError);
1690 result = NULL;
1691 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001692 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 if (len > PY_SSIZE_T_MAX) {
1694 PyErr_SetString(PyExc_OverflowError,
1695 "input: input too long");
1696 result = NULL;
1697 }
1698 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001699 len--; /* strip trailing '\n' */
1700 if (len != 0 && s[len-1] == '\r')
1701 len--; /* strip trailing '\r' */
1702 result = PyUnicode_Decode(s, len, stdin_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 }
1704 }
1705 Py_DECREF(stdin_encoding);
1706 PyMem_FREE(s);
1707 return result;
1708 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 /* Fallback if we're not interactive */
1711 if (promptarg != NULL) {
1712 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1713 return NULL;
1714 }
1715 tmp = PyObject_CallMethod(fout, "flush", "");
1716 if (tmp == NULL)
1717 PyErr_Clear();
1718 else
1719 Py_DECREF(tmp);
1720 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001721}
1722
1723PyDoc_STRVAR(input_doc,
1724"input([prompt]) -> string\n\
1725\n\
1726Read a string from standard input. The trailing newline is stripped.\n\
1727If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1728On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1729is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001730
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001731
Guido van Rossum79f25d91997-04-29 20:08:16 +00001732static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001733builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001736}
1737
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001738PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001739"repr(object) -> string\n\
1740\n\
1741Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001742For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001743
1744
Guido van Rossum79f25d91997-04-29 20:08:16 +00001745static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001746builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 static PyObject *round_str = NULL;
1749 PyObject *ndigits = NULL;
1750 static char *kwlist[] = {"number", "ndigits", 0};
1751 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1754 kwlist, &number, &ndigits))
1755 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 if (Py_TYPE(number)->tp_dict == NULL) {
1758 if (PyType_Ready(Py_TYPE(number)) < 0)
1759 return NULL;
1760 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 if (round_str == NULL) {
1763 round_str = PyUnicode_InternFromString("__round__");
1764 if (round_str == NULL)
1765 return NULL;
1766 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 round = _PyType_Lookup(Py_TYPE(number), round_str);
1769 if (round == NULL) {
1770 PyErr_Format(PyExc_TypeError,
1771 "type %.100s doesn't define __round__ method",
1772 Py_TYPE(number)->tp_name);
1773 return NULL;
1774 }
Alex Martelliae211f92007-08-22 23:21:33 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 if (ndigits == NULL)
1777 return PyObject_CallFunction(round, "O", number);
1778 else
1779 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001780}
1781
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001782PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001783"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001784\n\
1785Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001786This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001787same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001788
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001789
Raymond Hettinger64958a12003-12-17 20:43:33 +00001790static PyObject *
1791builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1794 PyObject *callable;
1795 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1796 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 /* args 1-3 should match listsort in Objects/listobject.c */
1799 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1800 kwlist, &seq, &keyfunc, &reverse))
1801 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 newlist = PySequence_List(seq);
1804 if (newlist == NULL)
1805 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 callable = PyObject_GetAttrString(newlist, "sort");
1808 if (callable == NULL) {
1809 Py_DECREF(newlist);
1810 return NULL;
1811 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 newargs = PyTuple_GetSlice(args, 1, 4);
1814 if (newargs == NULL) {
1815 Py_DECREF(newlist);
1816 Py_DECREF(callable);
1817 return NULL;
1818 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 v = PyObject_Call(callable, newargs, kwds);
1821 Py_DECREF(newargs);
1822 Py_DECREF(callable);
1823 if (v == NULL) {
1824 Py_DECREF(newlist);
1825 return NULL;
1826 }
1827 Py_DECREF(v);
1828 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001829}
1830
1831PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001832"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001833
Guido van Rossum79f25d91997-04-29 20:08:16 +00001834static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001835builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 PyObject *v = NULL;
1838 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1841 return NULL;
1842 if (v == NULL) {
1843 d = PyEval_GetLocals();
1844 if (d == NULL) {
1845 if (!PyErr_Occurred())
1846 PyErr_SetString(PyExc_SystemError,
1847 "vars(): no locals!?");
1848 }
1849 else
1850 Py_INCREF(d);
1851 }
1852 else {
1853 d = PyObject_GetAttrString(v, "__dict__");
1854 if (d == NULL) {
1855 PyErr_SetString(PyExc_TypeError,
1856 "vars() argument must have __dict__ attribute");
1857 return NULL;
1858 }
1859 }
1860 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001861}
1862
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001863PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001864"vars([object]) -> dictionary\n\
1865\n\
1866Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001867With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001868
Alex Martellia70b1912003-04-22 08:12:33 +00001869static PyObject*
1870builtin_sum(PyObject *self, PyObject *args)
1871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 PyObject *seq;
1873 PyObject *result = NULL;
1874 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1877 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 iter = PyObject_GetIter(seq);
1880 if (iter == NULL)
1881 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 if (result == NULL) {
1884 result = PyLong_FromLong(0);
1885 if (result == NULL) {
1886 Py_DECREF(iter);
1887 return NULL;
1888 }
1889 } else {
1890 /* reject string values for 'start' parameter */
1891 if (PyUnicode_Check(result)) {
1892 PyErr_SetString(PyExc_TypeError,
1893 "sum() can't sum strings [use ''.join(seq) instead]");
1894 Py_DECREF(iter);
1895 return NULL;
1896 }
1897 if (PyByteArray_Check(result)) {
1898 PyErr_SetString(PyExc_TypeError,
1899 "sum() can't sum bytes [use b''.join(seq) instead]");
1900 Py_DECREF(iter);
1901 return NULL;
1902 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 Py_INCREF(result);
1905 }
Alex Martellia70b1912003-04-22 08:12:33 +00001906
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001907#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1909 Assumes all inputs are the same type. If the assumption fails, default
1910 to the more general routine.
1911 */
1912 if (PyLong_CheckExact(result)) {
1913 int overflow;
1914 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1915 /* If this already overflowed, don't even enter the loop. */
1916 if (overflow == 0) {
1917 Py_DECREF(result);
1918 result = NULL;
1919 }
1920 while(result == NULL) {
1921 item = PyIter_Next(iter);
1922 if (item == NULL) {
1923 Py_DECREF(iter);
1924 if (PyErr_Occurred())
1925 return NULL;
1926 return PyLong_FromLong(i_result);
1927 }
1928 if (PyLong_CheckExact(item)) {
1929 long b = PyLong_AsLongAndOverflow(item, &overflow);
1930 long x = i_result + b;
1931 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1932 i_result = x;
1933 Py_DECREF(item);
1934 continue;
1935 }
1936 }
1937 /* Either overflowed or is not an int. Restore real objects and process normally */
1938 result = PyLong_FromLong(i_result);
1939 temp = PyNumber_Add(result, item);
1940 Py_DECREF(result);
1941 Py_DECREF(item);
1942 result = temp;
1943 if (result == NULL) {
1944 Py_DECREF(iter);
1945 return NULL;
1946 }
1947 }
1948 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 if (PyFloat_CheckExact(result)) {
1951 double f_result = PyFloat_AS_DOUBLE(result);
1952 Py_DECREF(result);
1953 result = NULL;
1954 while(result == NULL) {
1955 item = PyIter_Next(iter);
1956 if (item == NULL) {
1957 Py_DECREF(iter);
1958 if (PyErr_Occurred())
1959 return NULL;
1960 return PyFloat_FromDouble(f_result);
1961 }
1962 if (PyFloat_CheckExact(item)) {
1963 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1964 f_result += PyFloat_AS_DOUBLE(item);
1965 PyFPE_END_PROTECT(f_result)
1966 Py_DECREF(item);
1967 continue;
1968 }
1969 if (PyLong_CheckExact(item)) {
1970 long value;
1971 int overflow;
1972 value = PyLong_AsLongAndOverflow(item, &overflow);
1973 if (!overflow) {
1974 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1975 f_result += (double)value;
1976 PyFPE_END_PROTECT(f_result)
1977 Py_DECREF(item);
1978 continue;
1979 }
1980 }
1981 result = PyFloat_FromDouble(f_result);
1982 temp = PyNumber_Add(result, item);
1983 Py_DECREF(result);
1984 Py_DECREF(item);
1985 result = temp;
1986 if (result == NULL) {
1987 Py_DECREF(iter);
1988 return NULL;
1989 }
1990 }
1991 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001992#endif
1993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 for(;;) {
1995 item = PyIter_Next(iter);
1996 if (item == NULL) {
1997 /* error, or end-of-sequence */
1998 if (PyErr_Occurred()) {
1999 Py_DECREF(result);
2000 result = NULL;
2001 }
2002 break;
2003 }
2004 /* It's tempting to use PyNumber_InPlaceAdd instead of
2005 PyNumber_Add here, to avoid quadratic running time
2006 when doing 'sum(list_of_lists, [])'. However, this
2007 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 empty = []
2010 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 would change the value of empty. */
2013 temp = PyNumber_Add(result, item);
2014 Py_DECREF(result);
2015 Py_DECREF(item);
2016 result = temp;
2017 if (result == NULL)
2018 break;
2019 }
2020 Py_DECREF(iter);
2021 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002022}
2023
2024PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002025"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002026\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002027Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2028of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002029empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002030
2031
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002032static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002033builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 PyObject *inst;
2036 PyObject *cls;
2037 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2040 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 retval = PyObject_IsInstance(inst, cls);
2043 if (retval < 0)
2044 return NULL;
2045 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002046}
2047
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002048PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002049"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002050\n\
2051Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002052With a type as second argument, return whether that is the object's type.\n\
2053The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002054isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002055
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002056
2057static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002058builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 PyObject *derived;
2061 PyObject *cls;
2062 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2065 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 retval = PyObject_IsSubclass(derived, cls);
2068 if (retval < 0)
2069 return NULL;
2070 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002071}
2072
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002073PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002074"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002075\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002076Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2077When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2078is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002079
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002080
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002081typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 PyObject_HEAD
2083 Py_ssize_t tuplesize;
2084 PyObject *ittuple; /* tuple of iterators */
2085 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002086} zipobject;
2087
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002088static PyObject *
2089zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 zipobject *lz;
2092 Py_ssize_t i;
2093 PyObject *ittuple; /* tuple of iterators */
2094 PyObject *result;
2095 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2098 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 /* args must be a tuple */
2101 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 /* obtain iterators */
2104 ittuple = PyTuple_New(tuplesize);
2105 if (ittuple == NULL)
2106 return NULL;
2107 for (i=0; i < tuplesize; ++i) {
2108 PyObject *item = PyTuple_GET_ITEM(args, i);
2109 PyObject *it = PyObject_GetIter(item);
2110 if (it == NULL) {
2111 if (PyErr_ExceptionMatches(PyExc_TypeError))
2112 PyErr_Format(PyExc_TypeError,
2113 "zip argument #%zd must support iteration",
2114 i+1);
2115 Py_DECREF(ittuple);
2116 return NULL;
2117 }
2118 PyTuple_SET_ITEM(ittuple, i, it);
2119 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 /* create a result holder */
2122 result = PyTuple_New(tuplesize);
2123 if (result == NULL) {
2124 Py_DECREF(ittuple);
2125 return NULL;
2126 }
2127 for (i=0 ; i < tuplesize ; i++) {
2128 Py_INCREF(Py_None);
2129 PyTuple_SET_ITEM(result, i, Py_None);
2130 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 /* create zipobject structure */
2133 lz = (zipobject *)type->tp_alloc(type, 0);
2134 if (lz == NULL) {
2135 Py_DECREF(ittuple);
2136 Py_DECREF(result);
2137 return NULL;
2138 }
2139 lz->ittuple = ittuple;
2140 lz->tuplesize = tuplesize;
2141 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002144}
2145
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002146static void
2147zip_dealloc(zipobject *lz)
2148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 PyObject_GC_UnTrack(lz);
2150 Py_XDECREF(lz->ittuple);
2151 Py_XDECREF(lz->result);
2152 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002153}
2154
2155static int
2156zip_traverse(zipobject *lz, visitproc visit, void *arg)
2157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 Py_VISIT(lz->ittuple);
2159 Py_VISIT(lz->result);
2160 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002161}
2162
2163static PyObject *
2164zip_next(zipobject *lz)
2165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 Py_ssize_t i;
2167 Py_ssize_t tuplesize = lz->tuplesize;
2168 PyObject *result = lz->result;
2169 PyObject *it;
2170 PyObject *item;
2171 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 if (tuplesize == 0)
2174 return NULL;
2175 if (Py_REFCNT(result) == 1) {
2176 Py_INCREF(result);
2177 for (i=0 ; i < tuplesize ; i++) {
2178 it = PyTuple_GET_ITEM(lz->ittuple, i);
2179 item = (*Py_TYPE(it)->tp_iternext)(it);
2180 if (item == NULL) {
2181 Py_DECREF(result);
2182 return NULL;
2183 }
2184 olditem = PyTuple_GET_ITEM(result, i);
2185 PyTuple_SET_ITEM(result, i, item);
2186 Py_DECREF(olditem);
2187 }
2188 } else {
2189 result = PyTuple_New(tuplesize);
2190 if (result == NULL)
2191 return NULL;
2192 for (i=0 ; i < tuplesize ; i++) {
2193 it = PyTuple_GET_ITEM(lz->ittuple, i);
2194 item = (*Py_TYPE(it)->tp_iternext)(it);
2195 if (item == NULL) {
2196 Py_DECREF(result);
2197 return NULL;
2198 }
2199 PyTuple_SET_ITEM(result, i, item);
2200 }
2201 }
2202 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002203}
Barry Warsawbd599b52000-08-03 15:45:29 +00002204
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002205PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002206"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002207\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002208Return a zip object whose .__next__() method returns a tuple where\n\
2209the i-th element comes from the i-th iterable argument. The .__next__()\n\
2210method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002211is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002212
2213PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2215 "zip", /* tp_name */
2216 sizeof(zipobject), /* tp_basicsize */
2217 0, /* tp_itemsize */
2218 /* methods */
2219 (destructor)zip_dealloc, /* tp_dealloc */
2220 0, /* tp_print */
2221 0, /* tp_getattr */
2222 0, /* tp_setattr */
2223 0, /* tp_reserved */
2224 0, /* tp_repr */
2225 0, /* tp_as_number */
2226 0, /* tp_as_sequence */
2227 0, /* tp_as_mapping */
2228 0, /* tp_hash */
2229 0, /* tp_call */
2230 0, /* tp_str */
2231 PyObject_GenericGetAttr, /* tp_getattro */
2232 0, /* tp_setattro */
2233 0, /* tp_as_buffer */
2234 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2235 Py_TPFLAGS_BASETYPE, /* tp_flags */
2236 zip_doc, /* tp_doc */
2237 (traverseproc)zip_traverse, /* tp_traverse */
2238 0, /* tp_clear */
2239 0, /* tp_richcompare */
2240 0, /* tp_weaklistoffset */
2241 PyObject_SelfIter, /* tp_iter */
2242 (iternextfunc)zip_next, /* tp_iternext */
2243 0, /* tp_methods */
2244 0, /* tp_members */
2245 0, /* tp_getset */
2246 0, /* tp_base */
2247 0, /* tp_dict */
2248 0, /* tp_descr_get */
2249 0, /* tp_descr_set */
2250 0, /* tp_dictoffset */
2251 0, /* tp_init */
2252 PyType_GenericAlloc, /* tp_alloc */
2253 zip_new, /* tp_new */
2254 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002255};
Barry Warsawbd599b52000-08-03 15:45:29 +00002256
2257
Guido van Rossum79f25d91997-04-29 20:08:16 +00002258static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 {"__build_class__", (PyCFunction)builtin___build_class__,
2260 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2261 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2262 {"abs", builtin_abs, METH_O, abs_doc},
2263 {"all", builtin_all, METH_O, all_doc},
2264 {"any", builtin_any, METH_O, any_doc},
2265 {"ascii", builtin_ascii, METH_O, ascii_doc},
2266 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002267 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2269 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2270 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2271 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2272 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2273 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2274 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2275 {"format", builtin_format, METH_VARARGS, format_doc},
2276 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2277 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2278 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2279 {"hash", builtin_hash, METH_O, hash_doc},
2280 {"hex", builtin_hex, METH_O, hex_doc},
2281 {"id", builtin_id, METH_O, id_doc},
2282 {"input", builtin_input, METH_VARARGS, input_doc},
2283 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2284 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2285 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2286 {"len", builtin_len, METH_O, len_doc},
2287 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2288 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2289 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2290 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2291 {"oct", builtin_oct, METH_O, oct_doc},
2292 {"ord", builtin_ord, METH_O, ord_doc},
2293 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2294 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2295 {"repr", builtin_repr, METH_O, repr_doc},
2296 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2297 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2298 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2299 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2300 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2301 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002302};
2303
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002304PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002305"Built-in functions, exceptions, and other objects.\n\
2306\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002307Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002308
Martin v. Löwis1a214512008-06-11 05:26:20 +00002309static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 PyModuleDef_HEAD_INIT,
2311 "builtins",
2312 builtin_doc,
2313 -1, /* multiple "initialization" just copies the module dict. */
2314 builtin_methods,
2315 NULL,
2316 NULL,
2317 NULL,
2318 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002319};
2320
2321
Guido van Rossum25ce5661997-08-02 03:10:38 +00002322PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002323_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 PyObject *mod, *dict, *debug;
2326 mod = PyModule_Create(&builtinsmodule);
2327 if (mod == NULL)
2328 return NULL;
2329 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002330
Tim Peters7571a0f2003-03-23 17:52:28 +00002331#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 /* "builtins" exposes a number of statically allocated objects
2333 * that, before this code was added in 2.3, never showed up in
2334 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2335 * result, programs leaking references to None and False (etc)
2336 * couldn't be diagnosed by examining sys.getobjects(0).
2337 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002338#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2339#else
2340#define ADD_TO_ALL(OBJECT) (void)0
2341#endif
2342
Tim Peters4b7625e2001-09-13 21:37:17 +00002343#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2345 return NULL; \
2346 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 SETBUILTIN("None", Py_None);
2349 SETBUILTIN("Ellipsis", Py_Ellipsis);
2350 SETBUILTIN("NotImplemented", Py_NotImplemented);
2351 SETBUILTIN("False", Py_False);
2352 SETBUILTIN("True", Py_True);
2353 SETBUILTIN("bool", &PyBool_Type);
2354 SETBUILTIN("memoryview", &PyMemoryView_Type);
2355 SETBUILTIN("bytearray", &PyByteArray_Type);
2356 SETBUILTIN("bytes", &PyBytes_Type);
2357 SETBUILTIN("classmethod", &PyClassMethod_Type);
2358 SETBUILTIN("complex", &PyComplex_Type);
2359 SETBUILTIN("dict", &PyDict_Type);
2360 SETBUILTIN("enumerate", &PyEnum_Type);
2361 SETBUILTIN("filter", &PyFilter_Type);
2362 SETBUILTIN("float", &PyFloat_Type);
2363 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2364 SETBUILTIN("property", &PyProperty_Type);
2365 SETBUILTIN("int", &PyLong_Type);
2366 SETBUILTIN("list", &PyList_Type);
2367 SETBUILTIN("map", &PyMap_Type);
2368 SETBUILTIN("object", &PyBaseObject_Type);
2369 SETBUILTIN("range", &PyRange_Type);
2370 SETBUILTIN("reversed", &PyReversed_Type);
2371 SETBUILTIN("set", &PySet_Type);
2372 SETBUILTIN("slice", &PySlice_Type);
2373 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2374 SETBUILTIN("str", &PyUnicode_Type);
2375 SETBUILTIN("super", &PySuper_Type);
2376 SETBUILTIN("tuple", &PyTuple_Type);
2377 SETBUILTIN("type", &PyType_Type);
2378 SETBUILTIN("zip", &PyZip_Type);
2379 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2380 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2381 Py_XDECREF(debug);
2382 return NULL;
2383 }
2384 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002387#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002388#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002389}