blob: d05232c34af592a56d21cdf93d5746423b6db948 [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{
Nick Coghlande31b192011-10-23 22:04:16 +100038 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 PyObject *cls = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020040 Py_ssize_t nargs;
Nick Coghlande31b192011-10-23 22:04:16 +100041 int isclass;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043 assert(args != NULL);
44 if (!PyTuple_Check(args)) {
45 PyErr_SetString(PyExc_TypeError,
46 "__build_class__: args is not a tuple");
47 return NULL;
48 }
49 nargs = PyTuple_GET_SIZE(args);
50 if (nargs < 2) {
51 PyErr_SetString(PyExc_TypeError,
52 "__build_class__: not enough arguments");
53 return NULL;
54 }
55 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
56 name = PyTuple_GET_ITEM(args, 1);
57 if (!PyUnicode_Check(name)) {
58 PyErr_SetString(PyExc_TypeError,
59 "__build_class__: name is not a string");
60 return NULL;
61 }
62 bases = PyTuple_GetSlice(args, 2, nargs);
63 if (bases == NULL)
64 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000066 if (kwds == NULL) {
67 meta = NULL;
68 mkw = NULL;
69 }
70 else {
71 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
72 if (mkw == NULL) {
73 Py_DECREF(bases);
74 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000075 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 meta = PyDict_GetItemString(mkw, "metaclass");
77 if (meta != NULL) {
78 Py_INCREF(meta);
79 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
80 Py_DECREF(meta);
81 Py_DECREF(mkw);
82 Py_DECREF(bases);
83 return NULL;
84 }
Nick Coghlande31b192011-10-23 22:04:16 +100085 /* metaclass is explicitly given, check if it's indeed a class */
86 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 }
88 }
89 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +100090 /* if there are no bases, use type: */
91 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +100093 }
94 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 else {
96 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
97 meta = (PyObject *) (base0->ob_type);
98 }
99 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000100 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 }
Nick Coghlande31b192011-10-23 22:04:16 +1000102 if (isclass) {
103 /* meta is really a class, so check for a more derived
104 metaclass, or possible metaclass conflicts: */
105 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
106 bases);
107 if (winner == NULL) {
108 Py_DECREF(meta);
109 Py_XDECREF(mkw);
110 Py_DECREF(bases);
111 return NULL;
112 }
113 if (winner != meta) {
114 Py_DECREF(meta);
115 meta = winner;
116 Py_INCREF(meta);
117 }
118 }
119 /* else: meta is not a class, so we cannot do the metaclass
120 calculation, so we will use the explicitly given object as it is */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 prep = PyObject_GetAttrString(meta, "__prepare__");
122 if (prep == NULL) {
123 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
124 PyErr_Clear();
125 ns = PyDict_New();
126 }
127 else {
128 Py_DECREF(meta);
129 Py_XDECREF(mkw);
130 Py_DECREF(bases);
131 return NULL;
132 }
133 }
134 else {
135 PyObject *pargs = PyTuple_Pack(2, name, bases);
136 if (pargs == NULL) {
137 Py_DECREF(prep);
138 Py_DECREF(meta);
139 Py_XDECREF(mkw);
140 Py_DECREF(bases);
141 return NULL;
142 }
143 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
144 Py_DECREF(pargs);
145 Py_DECREF(prep);
146 }
147 if (ns == NULL) {
148 Py_DECREF(meta);
149 Py_XDECREF(mkw);
150 Py_DECREF(bases);
151 return NULL;
152 }
153 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
154 if (cell != NULL) {
155 PyObject *margs;
156 margs = PyTuple_Pack(3, name, bases, ns);
157 if (margs != NULL) {
158 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
159 Py_DECREF(margs);
160 }
161 if (cls != NULL && PyCell_Check(cell)) {
162 Py_INCREF(cls);
163 PyCell_SET(cell, cls);
164 }
165 Py_DECREF(cell);
166 }
167 Py_DECREF(ns);
168 Py_DECREF(meta);
169 Py_XDECREF(mkw);
170 Py_DECREF(bases);
171 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000172}
173
174PyDoc_STRVAR(build_class_doc,
175"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
176\n\
177Internal helper function used by the class statement.");
178
179static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000180builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
183 "level", 0};
184 char *name;
185 PyObject *globals = NULL;
186 PyObject *locals = NULL;
187 PyObject *fromlist = NULL;
188 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
191 kwlist, &name, &globals, &locals, &fromlist, &level))
192 return NULL;
193 return PyImport_ImportModuleLevel(name, globals, locals,
194 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000195}
196
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000197PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000198"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000199\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000200Import a module. Because this function is meant for use by the Python\n\
201interpreter and not for general use it is better to use\n\
202importlib.import_module() to programmatically import a module.\n\
203\n\
204The globals argument is only used to determine the context;\n\
205they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000206should be a list of names to emulate ``from name import ...'', or an\n\
207empty list to emulate ``import name''.\n\
208When importing a module from a package, note that __import__('A.B', ...)\n\
209returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000210fromlist is not empty. Level is used to determine whether to perform \n\
211absolute or relative imports. -1 is the original strategy of attempting\n\
212both absolute and relative imports, 0 is absolute, a positive number\n\
213is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000214
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000215
Guido van Rossum79f25d91997-04-29 20:08:16 +0000216static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000217builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000220}
221
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000222PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000223"abs(number) -> number\n\
224\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000225Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000226
Raymond Hettinger96229b12005-03-11 06:49:40 +0000227static PyObject *
228builtin_all(PyObject *self, PyObject *v)
229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 PyObject *it, *item;
231 PyObject *(*iternext)(PyObject *);
232 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 it = PyObject_GetIter(v);
235 if (it == NULL)
236 return NULL;
237 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 for (;;) {
240 item = iternext(it);
241 if (item == NULL)
242 break;
243 cmp = PyObject_IsTrue(item);
244 Py_DECREF(item);
245 if (cmp < 0) {
246 Py_DECREF(it);
247 return NULL;
248 }
249 if (cmp == 0) {
250 Py_DECREF(it);
251 Py_RETURN_FALSE;
252 }
253 }
254 Py_DECREF(it);
255 if (PyErr_Occurred()) {
256 if (PyErr_ExceptionMatches(PyExc_StopIteration))
257 PyErr_Clear();
258 else
259 return NULL;
260 }
261 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000262}
263
264PyDoc_STRVAR(all_doc,
265"all(iterable) -> bool\n\
266\n\
267Return True if bool(x) is True for all values x in the iterable.");
268
269static PyObject *
270builtin_any(PyObject *self, PyObject *v)
271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 PyObject *it, *item;
273 PyObject *(*iternext)(PyObject *);
274 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 it = PyObject_GetIter(v);
277 if (it == NULL)
278 return NULL;
279 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 for (;;) {
282 item = iternext(it);
283 if (item == NULL)
284 break;
285 cmp = PyObject_IsTrue(item);
286 Py_DECREF(item);
287 if (cmp < 0) {
288 Py_DECREF(it);
289 return NULL;
290 }
291 if (cmp == 1) {
292 Py_DECREF(it);
293 Py_RETURN_TRUE;
294 }
295 }
296 Py_DECREF(it);
297 if (PyErr_Occurred()) {
298 if (PyErr_ExceptionMatches(PyExc_StopIteration))
299 PyErr_Clear();
300 else
301 return NULL;
302 }
303 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000304}
305
306PyDoc_STRVAR(any_doc,
307"any(iterable) -> bool\n\
308\n\
309Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000310
Georg Brandl559e5d72008-06-11 18:37:52 +0000311static PyObject *
312builtin_ascii(PyObject *self, PyObject *v)
313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000315}
316
317PyDoc_STRVAR(ascii_doc,
318"ascii(object) -> string\n\
319\n\
320As repr(), return a string containing a printable representation of an\n\
321object, but escape the non-ASCII characters in the string returned by\n\
322repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
323to that returned by repr() in Python 2.");
324
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000325
Guido van Rossum79f25d91997-04-29 20:08:16 +0000326static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000327builtin_bin(PyObject *self, PyObject *v)
328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000330}
331
332PyDoc_STRVAR(bin_doc,
333"bin(number) -> string\n\
334\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -0400335Return the binary representation of an integer.");
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000336
337
Antoine Pitroue71362d2010-11-27 22:00:11 +0000338static PyObject *
339builtin_callable(PyObject *self, PyObject *v)
340{
341 return PyBool_FromLong((long)PyCallable_Check(v));
342}
343
344PyDoc_STRVAR(callable_doc,
345"callable(object) -> bool\n\
346\n\
347Return whether the object is callable (i.e., some kind of function).\n\
348Note that classes are callable, as are instances of classes with a\n\
349__call__() method.");
350
351
Raymond Hettinger17301e92008-03-13 00:19:26 +0000352typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 PyObject_HEAD
354 PyObject *func;
355 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000356} filterobject;
357
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000358static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000359filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 PyObject *func, *seq;
362 PyObject *it;
363 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
366 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
369 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 /* Get iterator. */
372 it = PyObject_GetIter(seq);
373 if (it == NULL)
374 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 /* create filterobject structure */
377 lz = (filterobject *)type->tp_alloc(type, 0);
378 if (lz == NULL) {
379 Py_DECREF(it);
380 return NULL;
381 }
382 Py_INCREF(func);
383 lz->func = func;
384 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000387}
388
389static void
390filter_dealloc(filterobject *lz)
391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 PyObject_GC_UnTrack(lz);
393 Py_XDECREF(lz->func);
394 Py_XDECREF(lz->it);
395 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000396}
397
398static int
399filter_traverse(filterobject *lz, visitproc visit, void *arg)
400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 Py_VISIT(lz->it);
402 Py_VISIT(lz->func);
403 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000404}
405
406static PyObject *
407filter_next(filterobject *lz)
408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 PyObject *item;
410 PyObject *it = lz->it;
411 long ok;
412 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 iternext = *Py_TYPE(it)->tp_iternext;
415 for (;;) {
416 item = iternext(it);
417 if (item == NULL)
418 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
421 ok = PyObject_IsTrue(item);
422 } else {
423 PyObject *good;
424 good = PyObject_CallFunctionObjArgs(lz->func,
425 item, NULL);
426 if (good == NULL) {
427 Py_DECREF(item);
428 return NULL;
429 }
430 ok = PyObject_IsTrue(good);
431 Py_DECREF(good);
432 }
433 if (ok)
434 return item;
435 Py_DECREF(item);
436 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000437}
438
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000439PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000440"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000441\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000442Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000443is true. If function is None, return the items that are true.");
444
445PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 PyVarObject_HEAD_INIT(&PyType_Type, 0)
447 "filter", /* tp_name */
448 sizeof(filterobject), /* tp_basicsize */
449 0, /* tp_itemsize */
450 /* methods */
451 (destructor)filter_dealloc, /* tp_dealloc */
452 0, /* tp_print */
453 0, /* tp_getattr */
454 0, /* tp_setattr */
455 0, /* tp_reserved */
456 0, /* tp_repr */
457 0, /* tp_as_number */
458 0, /* tp_as_sequence */
459 0, /* tp_as_mapping */
460 0, /* tp_hash */
461 0, /* tp_call */
462 0, /* tp_str */
463 PyObject_GenericGetAttr, /* tp_getattro */
464 0, /* tp_setattro */
465 0, /* tp_as_buffer */
466 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
467 Py_TPFLAGS_BASETYPE, /* tp_flags */
468 filter_doc, /* tp_doc */
469 (traverseproc)filter_traverse, /* tp_traverse */
470 0, /* tp_clear */
471 0, /* tp_richcompare */
472 0, /* tp_weaklistoffset */
473 PyObject_SelfIter, /* tp_iter */
474 (iternextfunc)filter_next, /* tp_iternext */
475 0, /* tp_methods */
476 0, /* tp_members */
477 0, /* tp_getset */
478 0, /* tp_base */
479 0, /* tp_dict */
480 0, /* tp_descr_get */
481 0, /* tp_descr_set */
482 0, /* tp_dictoffset */
483 0, /* tp_init */
484 PyType_GenericAlloc, /* tp_alloc */
485 filter_new, /* tp_new */
486 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000487};
488
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000489
Eric Smith8c663262007-08-25 02:26:07 +0000490static PyObject *
491builtin_format(PyObject *self, PyObject *args)
492{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000493 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000494 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000495
Eric Smith8fd3eba2008-02-17 19:48:00 +0000496 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000498
Eric Smith8fd3eba2008-02-17 19:48:00 +0000499 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000500}
501
Eric Smith8c663262007-08-25 02:26:07 +0000502PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000503"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000504\n\
Eric Smith81936692007-08-31 01:14:01 +0000505Returns value.__format__(format_spec)\n\
506format_spec defaults to \"\"");
507
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000508static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000509builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 if (!PyArg_ParseTuple(args, "i:chr", &x))
514 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000517}
518
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000519PyDoc_VAR(chr_doc) = PyDoc_STR(
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000520"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000521\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000522Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000523)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000524#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000525PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000526"\nIf 0x10000 <= i, a surrogate pair is returned."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000527)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000528#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000529;
Guido van Rossum09095f32000-03-10 23:00:52 +0000530
531
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000532static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000533source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 char *str;
536 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (PyUnicode_Check(cmd)) {
539 cf->cf_flags |= PyCF_IGNORE_COOKIE;
540 cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL);
541 if (cmd == NULL)
542 return NULL;
543 }
544 else if (!PyObject_CheckReadBuffer(cmd)) {
545 PyErr_Format(PyExc_TypeError,
546 "%s() arg 1 must be a %s object",
547 funcname, what);
548 return NULL;
549 }
550 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
551 return NULL;
552 }
553 if (strlen(str) != size) {
554 PyErr_SetString(PyExc_TypeError,
555 "source code string cannot contain null bytes");
556 return NULL;
557 }
558 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000559}
560
Guido van Rossum79f25d91997-04-29 20:08:16 +0000561static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000562builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 char *str;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000565 PyObject *filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 char *filename;
567 char *startstr;
568 int mode = -1;
569 int dont_inherit = 0;
570 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000571 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 int is_ast;
573 PyCompilerFlags cf;
574 PyObject *cmd;
575 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000576 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000578 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000579
Georg Brandl8334fd92010-12-04 10:26:46 +0000580 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000581 &cmd,
582 PyUnicode_FSConverter, &filename_obj,
583 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000584 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000586
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000587 filename = PyBytes_AS_STRING(filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 if (supplied_flags &
591 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
592 {
593 PyErr_SetString(PyExc_ValueError,
594 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000595 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 }
597 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000598
Georg Brandl8334fd92010-12-04 10:26:46 +0000599 if (optimize < -1 || optimize > 2) {
600 PyErr_SetString(PyExc_ValueError,
601 "compile(): invalid optimize value");
602 goto error;
603 }
604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 if (!dont_inherit) {
606 PyEval_MergeCompilerFlags(&cf);
607 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (strcmp(startstr, "exec") == 0)
610 mode = 0;
611 else if (strcmp(startstr, "eval") == 0)
612 mode = 1;
613 else if (strcmp(startstr, "single") == 0)
614 mode = 2;
615 else {
616 PyErr_SetString(PyExc_ValueError,
617 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000618 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 is_ast = PyAST_Check(cmd);
622 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000623 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 if (supplied_flags & PyCF_ONLY_AST) {
626 Py_INCREF(cmd);
627 result = cmd;
628 }
629 else {
630 PyArena *arena;
631 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 arena = PyArena_New();
634 mod = PyAST_obj2mod(cmd, arena, mode);
635 if (mod == NULL) {
636 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000637 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 }
Georg Brandl8334fd92010-12-04 10:26:46 +0000639 result = (PyObject*)PyAST_CompileEx(mod, filename,
640 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 PyArena_Free(arena);
642 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000643 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
647 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000648 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000649
Georg Brandl8334fd92010-12-04 10:26:46 +0000650 result = Py_CompileStringExFlags(str, filename, start[mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000651 goto finally;
652
653error:
654 result = NULL;
655finally:
656 Py_DECREF(filename_obj);
657 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000658}
659
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000660PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000661"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000662\n\
663Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000664into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000665The filename will be used for run-time error messages.\n\
666The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000667single (interactive) statement, or 'eval' to compile an expression.\n\
668The flags argument, if present, controls which future statements influence\n\
669the compilation of the code.\n\
670The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
671the effects of any future statements in effect in the code calling\n\
672compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000673in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000674
Guido van Rossum79f25d91997-04-29 20:08:16 +0000675static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000676builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
681 return NULL;
682 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000683}
684
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000685PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000686"dir([object]) -> list of strings\n"
687"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000688"If called without an argument, return the names in the current scope.\n"
689"Else, return an alphabetized list of names comprising (some of) the attributes\n"
690"of the given object, and of attributes reachable from it.\n"
691"If the object supplies a method named __dir__, it will be used; otherwise\n"
692"the default dir() logic is used and returns:\n"
693" for a module object: the module's attributes.\n"
694" for a class object: its attributes, and recursively the attributes\n"
695" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000696" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000697" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000698
Guido van Rossum79f25d91997-04-29 20:08:16 +0000699static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000700builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
705 return NULL;
706 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000707}
708
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000709PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000710"divmod(x, y) -> (div, mod)\n\
711\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000712Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000713
714
Guido van Rossum79f25d91997-04-29 20:08:16 +0000715static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000716builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 PyObject *cmd, *result, *tmp = NULL;
719 PyObject *globals = Py_None, *locals = Py_None;
720 char *str;
721 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
724 return NULL;
725 if (locals != Py_None && !PyMapping_Check(locals)) {
726 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
727 return NULL;
728 }
729 if (globals != Py_None && !PyDict_Check(globals)) {
730 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
731 "globals must be a real dict; try eval(expr, {}, mapping)"
732 : "globals must be a dict");
733 return NULL;
734 }
735 if (globals == Py_None) {
736 globals = PyEval_GetGlobals();
737 if (locals == Py_None)
738 locals = PyEval_GetLocals();
739 }
740 else if (locals == Py_None)
741 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 if (globals == NULL || locals == NULL) {
744 PyErr_SetString(PyExc_TypeError,
745 "eval must be given globals and locals "
746 "when called without a frame");
747 return NULL;
748 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
751 if (PyDict_SetItemString(globals, "__builtins__",
752 PyEval_GetBuiltins()) != 0)
753 return NULL;
754 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 if (PyCode_Check(cmd)) {
757 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
758 PyErr_SetString(PyExc_TypeError,
759 "code object passed to eval() may not contain free variables");
760 return NULL;
761 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000762 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
766 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
767 if (str == NULL)
768 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 while (*str == ' ' || *str == '\t')
771 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 (void)PyEval_MergeCompilerFlags(&cf);
774 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
775 Py_XDECREF(tmp);
776 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000777}
778
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000779PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000780"eval(source[, globals[, locals]]) -> value\n\
781\n\
782Evaluate the source in the context of globals and locals.\n\
783The source may be a string representing a Python expression\n\
784or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000785The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000786defaulting to the current globals and locals.\n\
787If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000788
Georg Brandl7cae87c2006-09-06 06:51:57 +0000789static PyObject *
790builtin_exec(PyObject *self, PyObject *args)
791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 PyObject *v;
793 PyObject *prog, *globals = Py_None, *locals = Py_None;
794 int plain = 0;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
797 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 if (globals == Py_None) {
800 globals = PyEval_GetGlobals();
801 if (locals == Py_None) {
802 locals = PyEval_GetLocals();
803 plain = 1;
804 }
805 if (!globals || !locals) {
806 PyErr_SetString(PyExc_SystemError,
807 "globals and locals cannot be NULL");
808 return NULL;
809 }
810 }
811 else if (locals == Py_None)
812 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 if (!PyDict_Check(globals)) {
815 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
816 globals->ob_type->tp_name);
817 return NULL;
818 }
819 if (!PyMapping_Check(locals)) {
820 PyErr_Format(PyExc_TypeError,
821 "arg 3 must be a mapping or None, not %.100s",
822 locals->ob_type->tp_name);
823 return NULL;
824 }
825 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
826 if (PyDict_SetItemString(globals, "__builtins__",
827 PyEval_GetBuiltins()) != 0)
828 return NULL;
829 }
830
831 if (PyCode_Check(prog)) {
832 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
833 PyErr_SetString(PyExc_TypeError,
834 "code object passed to exec() may not "
835 "contain free variables");
836 return NULL;
837 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000838 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 }
840 else {
841 char *str;
842 PyCompilerFlags cf;
843 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
844 str = source_as_string(prog, "exec",
845 "string, bytes or code", &cf);
846 if (str == NULL)
847 return NULL;
848 if (PyEval_MergeCompilerFlags(&cf))
849 v = PyRun_StringFlags(str, Py_file_input, globals,
850 locals, &cf);
851 else
852 v = PyRun_String(str, Py_file_input, globals, locals);
853 }
854 if (v == NULL)
855 return NULL;
856 Py_DECREF(v);
857 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000858}
859
860PyDoc_STRVAR(exec_doc,
861"exec(object[, globals[, locals]])\n\
862\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000863Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000864object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000865The globals and locals are dictionaries, defaulting to the current\n\
866globals and locals. If only globals is given, locals defaults to it.");
867
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000868
Guido van Rossum79f25d91997-04-29 20:08:16 +0000869static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000870builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 PyObject *v, *result, *dflt = NULL;
873 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
876 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 if (!PyUnicode_Check(name)) {
879 PyErr_SetString(PyExc_TypeError,
880 "getattr(): attribute name must be string");
881 return NULL;
882 }
883 result = PyObject_GetAttr(v, name);
884 if (result == NULL && dflt != NULL &&
885 PyErr_ExceptionMatches(PyExc_AttributeError))
886 {
887 PyErr_Clear();
888 Py_INCREF(dflt);
889 result = dflt;
890 }
891 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000892}
893
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000894PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000895"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000896\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000897Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
898When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000899exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000900
901
Guido van Rossum79f25d91997-04-29 20:08:16 +0000902static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000903builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 d = PyEval_GetGlobals();
908 Py_XINCREF(d);
909 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000910}
911
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000912PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000913"globals() -> dictionary\n\
914\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000915Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000916
917
Guido van Rossum79f25d91997-04-29 20:08:16 +0000918static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000919builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 PyObject *v;
922 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
925 return NULL;
926 if (!PyUnicode_Check(name)) {
927 PyErr_SetString(PyExc_TypeError,
928 "hasattr(): attribute name must be string");
929 return NULL;
930 }
931 v = PyObject_GetAttr(v, name);
932 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000933 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000935 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000937 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 }
939 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000940 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000941}
942
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000943PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000944"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000945\n\
946Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000947(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000948
949
Guido van Rossum79f25d91997-04-29 20:08:16 +0000950static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000951builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000954}
955
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000956PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000957"id(object) -> integer\n\
958\n\
959Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000960simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000961
962
Raymond Hettingera6c60372008-03-13 01:26:19 +0000963/* map object ************************************************************/
964
965typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 PyObject_HEAD
967 PyObject *iters;
968 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000969} mapobject;
970
Guido van Rossum79f25d91997-04-29 20:08:16 +0000971static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000972map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 PyObject *it, *iters, *func;
975 mapobject *lz;
976 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
979 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 numargs = PyTuple_Size(args);
982 if (numargs < 2) {
983 PyErr_SetString(PyExc_TypeError,
984 "map() must have at least two arguments.");
985 return NULL;
986 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 iters = PyTuple_New(numargs-1);
989 if (iters == NULL)
990 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 for (i=1 ; i<numargs ; i++) {
993 /* Get iterator. */
994 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
995 if (it == NULL) {
996 Py_DECREF(iters);
997 return NULL;
998 }
999 PyTuple_SET_ITEM(iters, i-1, it);
1000 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 /* create mapobject structure */
1003 lz = (mapobject *)type->tp_alloc(type, 0);
1004 if (lz == NULL) {
1005 Py_DECREF(iters);
1006 return NULL;
1007 }
1008 lz->iters = iters;
1009 func = PyTuple_GET_ITEM(args, 0);
1010 Py_INCREF(func);
1011 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001014}
1015
1016static void
1017map_dealloc(mapobject *lz)
1018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 PyObject_GC_UnTrack(lz);
1020 Py_XDECREF(lz->iters);
1021 Py_XDECREF(lz->func);
1022 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001023}
1024
1025static int
1026map_traverse(mapobject *lz, visitproc visit, void *arg)
1027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 Py_VISIT(lz->iters);
1029 Py_VISIT(lz->func);
1030 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001031}
1032
1033static PyObject *
1034map_next(mapobject *lz)
1035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 PyObject *val;
1037 PyObject *argtuple;
1038 PyObject *result;
1039 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 numargs = PyTuple_Size(lz->iters);
1042 argtuple = PyTuple_New(numargs);
1043 if (argtuple == NULL)
1044 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 for (i=0 ; i<numargs ; i++) {
1047 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1048 if (val == NULL) {
1049 Py_DECREF(argtuple);
1050 return NULL;
1051 }
1052 PyTuple_SET_ITEM(argtuple, i, val);
1053 }
1054 result = PyObject_Call(lz->func, argtuple, NULL);
1055 Py_DECREF(argtuple);
1056 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001057}
1058
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001059PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001060"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001061\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001062Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001064
Raymond Hettingera6c60372008-03-13 01:26:19 +00001065PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1067 "map", /* tp_name */
1068 sizeof(mapobject), /* tp_basicsize */
1069 0, /* tp_itemsize */
1070 /* methods */
1071 (destructor)map_dealloc, /* tp_dealloc */
1072 0, /* tp_print */
1073 0, /* tp_getattr */
1074 0, /* tp_setattr */
1075 0, /* tp_reserved */
1076 0, /* tp_repr */
1077 0, /* tp_as_number */
1078 0, /* tp_as_sequence */
1079 0, /* tp_as_mapping */
1080 0, /* tp_hash */
1081 0, /* tp_call */
1082 0, /* tp_str */
1083 PyObject_GenericGetAttr, /* tp_getattro */
1084 0, /* tp_setattro */
1085 0, /* tp_as_buffer */
1086 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1087 Py_TPFLAGS_BASETYPE, /* tp_flags */
1088 map_doc, /* tp_doc */
1089 (traverseproc)map_traverse, /* tp_traverse */
1090 0, /* tp_clear */
1091 0, /* tp_richcompare */
1092 0, /* tp_weaklistoffset */
1093 PyObject_SelfIter, /* tp_iter */
1094 (iternextfunc)map_next, /* tp_iternext */
1095 0, /* tp_methods */
1096 0, /* tp_members */
1097 0, /* tp_getset */
1098 0, /* tp_base */
1099 0, /* tp_dict */
1100 0, /* tp_descr_get */
1101 0, /* tp_descr_set */
1102 0, /* tp_dictoffset */
1103 0, /* tp_init */
1104 PyType_GenericAlloc, /* tp_alloc */
1105 map_new, /* tp_new */
1106 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001107};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001108
Guido van Rossum79f25d91997-04-29 20:08:16 +00001109static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001110builtin_next(PyObject *self, PyObject *args)
1111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 PyObject *it, *res;
1113 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1116 return NULL;
1117 if (!PyIter_Check(it)) {
1118 PyErr_Format(PyExc_TypeError,
1119 "%.200s object is not an iterator",
1120 it->ob_type->tp_name);
1121 return NULL;
1122 }
1123
1124 res = (*it->ob_type->tp_iternext)(it);
1125 if (res != NULL) {
1126 return res;
1127 } else if (def != NULL) {
1128 if (PyErr_Occurred()) {
1129 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1130 return NULL;
1131 PyErr_Clear();
1132 }
1133 Py_INCREF(def);
1134 return def;
1135 } else if (PyErr_Occurred()) {
1136 return NULL;
1137 } else {
1138 PyErr_SetNone(PyExc_StopIteration);
1139 return NULL;
1140 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001141}
1142
1143PyDoc_STRVAR(next_doc,
1144"next(iterator[, default])\n\
1145\n\
1146Return the next item from the iterator. If default is given and the iterator\n\
1147is exhausted, it is returned instead of raising StopIteration.");
1148
1149
1150static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001151builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 PyObject *v;
1154 PyObject *name;
1155 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1158 return NULL;
1159 if (PyObject_SetAttr(v, name, value) != 0)
1160 return NULL;
1161 Py_INCREF(Py_None);
1162 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001163}
1164
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001165PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001166"setattr(object, name, value)\n\
1167\n\
1168Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001169``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001170
1171
Guido van Rossum79f25d91997-04-29 20:08:16 +00001172static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001173builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 PyObject *v;
1176 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1179 return NULL;
1180 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1181 return NULL;
1182 Py_INCREF(Py_None);
1183 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001184}
1185
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001186PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001187"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001188\n\
1189Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001190``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001191
1192
Guido van Rossum79f25d91997-04-29 20:08:16 +00001193static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001194builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001195{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001196 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 x = PyObject_Hash(v);
1199 if (x == -1)
1200 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001201 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001202}
1203
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001204PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001205"hash(object) -> integer\n\
1206\n\
1207Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001208the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001209
1210
Guido van Rossum79f25d91997-04-29 20:08:16 +00001211static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001212builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001215}
1216
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001217PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001218"hex(number) -> string\n\
1219\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001220Return the hexadecimal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001221
1222
Guido van Rossum79f25d91997-04-29 20:08:16 +00001223static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001224builtin_iter(PyObject *self, PyObject *args)
1225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1229 return NULL;
1230 if (w == NULL)
1231 return PyObject_GetIter(v);
1232 if (!PyCallable_Check(v)) {
1233 PyErr_SetString(PyExc_TypeError,
1234 "iter(v, w): v must be callable");
1235 return NULL;
1236 }
1237 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001238}
1239
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001240PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001241"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001242iter(callable, sentinel) -> iterator\n\
1243\n\
1244Get an iterator from an object. In the first form, the argument must\n\
1245supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001246In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001247
1248
1249static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001250builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 res = PyObject_Size(v);
1255 if (res < 0 && PyErr_Occurred())
1256 return NULL;
1257 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001258}
1259
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001260PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001261"len(object) -> integer\n\
1262\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001263Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001264
1265
Guido van Rossum79f25d91997-04-29 20:08:16 +00001266static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001267builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 d = PyEval_GetLocals();
1272 Py_XINCREF(d);
1273 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001274}
1275
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001276PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001277"locals() -> dictionary\n\
1278\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001279Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001280
1281
Guido van Rossum79f25d91997-04-29 20:08:16 +00001282static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001283min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1286 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 if (PyTuple_Size(args) > 1)
1289 v = args;
1290 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1291 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1294 keyfunc = PyDict_GetItemString(kwds, "key");
1295 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1296 PyErr_Format(PyExc_TypeError,
1297 "%s() got an unexpected keyword argument", name);
1298 return NULL;
1299 }
1300 Py_INCREF(keyfunc);
1301 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 it = PyObject_GetIter(v);
1304 if (it == NULL) {
1305 Py_XDECREF(keyfunc);
1306 return NULL;
1307 }
Tim Petersc3074532001-05-03 07:00:32 +00001308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 maxitem = NULL; /* the result */
1310 maxval = NULL; /* the value associated with the result */
1311 while (( item = PyIter_Next(it) )) {
1312 /* get the value from the key function */
1313 if (keyfunc != NULL) {
1314 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1315 if (val == NULL)
1316 goto Fail_it_item;
1317 }
1318 /* no key function; the value is the item */
1319 else {
1320 val = item;
1321 Py_INCREF(val);
1322 }
Tim Petersc3074532001-05-03 07:00:32 +00001323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 /* maximum value and item are unset; set them */
1325 if (maxval == NULL) {
1326 maxitem = item;
1327 maxval = val;
1328 }
1329 /* maximum value and item are set; update them as necessary */
1330 else {
1331 int cmp = PyObject_RichCompareBool(val, maxval, op);
1332 if (cmp < 0)
1333 goto Fail_it_item_and_val;
1334 else if (cmp > 0) {
1335 Py_DECREF(maxval);
1336 Py_DECREF(maxitem);
1337 maxval = val;
1338 maxitem = item;
1339 }
1340 else {
1341 Py_DECREF(item);
1342 Py_DECREF(val);
1343 }
1344 }
1345 }
1346 if (PyErr_Occurred())
1347 goto Fail_it;
1348 if (maxval == NULL) {
1349 PyErr_Format(PyExc_ValueError,
1350 "%s() arg is an empty sequence", name);
1351 assert(maxitem == NULL);
1352 }
1353 else
1354 Py_DECREF(maxval);
1355 Py_DECREF(it);
1356 Py_XDECREF(keyfunc);
1357 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001358
1359Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001361Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001363Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 Py_XDECREF(maxval);
1365 Py_XDECREF(maxitem);
1366 Py_DECREF(it);
1367 Py_XDECREF(keyfunc);
1368 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001369}
1370
Guido van Rossum79f25d91997-04-29 20:08:16 +00001371static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001372builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001375}
1376
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001377PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001378"min(iterable[, key=func]) -> value\n\
1379min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001380\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001381With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001382With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001383
1384
Guido van Rossum79f25d91997-04-29 20:08:16 +00001385static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001386builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001389}
1390
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001391PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001392"max(iterable[, key=func]) -> value\n\
1393max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001394\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001395With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001396With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001397
1398
Guido van Rossum79f25d91997-04-29 20:08:16 +00001399static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001400builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001403}
1404
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001405PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001406"oct(number) -> string\n\
1407\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001408Return the octal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001409
1410
Guido van Rossum79f25d91997-04-29 20:08:16 +00001411static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001412builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 long ord;
1415 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 if (PyBytes_Check(obj)) {
1418 size = PyBytes_GET_SIZE(obj);
1419 if (size == 1) {
1420 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1421 return PyLong_FromLong(ord);
1422 }
1423 }
1424 else if (PyUnicode_Check(obj)) {
1425 size = PyUnicode_GET_SIZE(obj);
1426 if (size == 1) {
1427 ord = (long)*PyUnicode_AS_UNICODE(obj);
1428 return PyLong_FromLong(ord);
1429 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001430#ifndef Py_UNICODE_WIDE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 if (size == 2) {
1432 /* Decode a valid surrogate pair */
1433 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1434 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1435 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1436 0xDC00 <= c1 && c1 <= 0xDFFF) {
1437 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1438 0x00010000);
1439 return PyLong_FromLong(ord);
1440 }
1441 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001442#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 }
1444 else if (PyByteArray_Check(obj)) {
1445 /* XXX Hopefully this is temporary */
1446 size = PyByteArray_GET_SIZE(obj);
1447 if (size == 1) {
1448 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1449 return PyLong_FromLong(ord);
1450 }
1451 }
1452 else {
1453 PyErr_Format(PyExc_TypeError,
1454 "ord() expected string of length 1, but " \
1455 "%.200s found", obj->ob_type->tp_name);
1456 return NULL;
1457 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 PyErr_Format(PyExc_TypeError,
1460 "ord() expected a character, "
1461 "but string of length %zd found",
1462 size);
1463 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001464}
1465
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001466PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001467"ord(c) -> integer\n\
1468\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001469Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001470)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001471#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001472PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001473"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001474)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001475#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001476;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001477
1478
Guido van Rossum79f25d91997-04-29 20:08:16 +00001479static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001480builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1485 return NULL;
1486 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001487}
1488
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001489PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001490"pow(x, y[, z]) -> number\n\
1491\n\
1492With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001493equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001494
1495
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001496
Guido van Rossum34343512006-11-30 22:13:52 +00001497static PyObject *
1498builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 static char *kwlist[] = {"sep", "end", "file", 0};
1501 static PyObject *dummy_args;
1502 PyObject *sep = NULL, *end = NULL, *file = NULL;
1503 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 if (dummy_args == NULL) {
1506 if (!(dummy_args = PyTuple_New(0)))
1507 return NULL;
1508 }
1509 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1510 kwlist, &sep, &end, &file))
1511 return NULL;
1512 if (file == NULL || file == Py_None) {
1513 file = PySys_GetObject("stdout");
1514 /* sys.stdout may be None when FILE* stdout isn't connected */
1515 if (file == Py_None)
1516 Py_RETURN_NONE;
1517 }
Guido van Rossum34343512006-11-30 22:13:52 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 if (sep == Py_None) {
1520 sep = NULL;
1521 }
1522 else if (sep && !PyUnicode_Check(sep)) {
1523 PyErr_Format(PyExc_TypeError,
1524 "sep must be None or a string, not %.200s",
1525 sep->ob_type->tp_name);
1526 return NULL;
1527 }
1528 if (end == Py_None) {
1529 end = NULL;
1530 }
1531 else if (end && !PyUnicode_Check(end)) {
1532 PyErr_Format(PyExc_TypeError,
1533 "end must be None or a string, not %.200s",
1534 end->ob_type->tp_name);
1535 return NULL;
1536 }
Guido van Rossum34343512006-11-30 22:13:52 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 for (i = 0; i < PyTuple_Size(args); i++) {
1539 if (i > 0) {
1540 if (sep == NULL)
1541 err = PyFile_WriteString(" ", file);
1542 else
1543 err = PyFile_WriteObject(sep, file,
1544 Py_PRINT_RAW);
1545 if (err)
1546 return NULL;
1547 }
1548 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1549 Py_PRINT_RAW);
1550 if (err)
1551 return NULL;
1552 }
Guido van Rossum34343512006-11-30 22:13:52 +00001553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 if (end == NULL)
1555 err = PyFile_WriteString("\n", file);
1556 else
1557 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1558 if (err)
1559 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001562}
1563
1564PyDoc_STRVAR(print_doc,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001565"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001566\n\
1567Prints the values to a stream, or to sys.stdout by default.\n\
1568Optional keyword arguments:\n\
1569file: a file-like object (stream); defaults to the current sys.stdout.\n\
1570sep: string inserted between values, default a space.\n\
1571end: string appended after the last value, default a newline.");
1572
1573
Guido van Rossuma88a0332007-02-26 16:59:55 +00001574static PyObject *
1575builtin_input(PyObject *self, PyObject *args)
1576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 PyObject *promptarg = NULL;
1578 PyObject *fin = PySys_GetObject("stdin");
1579 PyObject *fout = PySys_GetObject("stdout");
1580 PyObject *ferr = PySys_GetObject("stderr");
1581 PyObject *tmp;
1582 long fd;
1583 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 /* Parse arguments */
1586 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1587 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 /* Check that stdin/out/err are intact */
1590 if (fin == NULL || fin == Py_None) {
1591 PyErr_SetString(PyExc_RuntimeError,
1592 "input(): lost sys.stdin");
1593 return NULL;
1594 }
1595 if (fout == NULL || fout == Py_None) {
1596 PyErr_SetString(PyExc_RuntimeError,
1597 "input(): lost sys.stdout");
1598 return NULL;
1599 }
1600 if (ferr == NULL || ferr == Py_None) {
1601 PyErr_SetString(PyExc_RuntimeError,
1602 "input(): lost sys.stderr");
1603 return NULL;
1604 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 /* First of all, flush stderr */
1607 tmp = PyObject_CallMethod(ferr, "flush", "");
1608 if (tmp == NULL)
1609 PyErr_Clear();
1610 else
1611 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 /* We should only use (GNU) readline if Python's sys.stdin and
1614 sys.stdout are the same as C's stdin and stdout, because we
1615 need to pass it those. */
1616 tmp = PyObject_CallMethod(fin, "fileno", "");
1617 if (tmp == NULL) {
1618 PyErr_Clear();
1619 tty = 0;
1620 }
1621 else {
1622 fd = PyLong_AsLong(tmp);
1623 Py_DECREF(tmp);
1624 if (fd < 0 && PyErr_Occurred())
1625 return NULL;
1626 tty = fd == fileno(stdin) && isatty(fd);
1627 }
1628 if (tty) {
1629 tmp = PyObject_CallMethod(fout, "fileno", "");
1630 if (tmp == NULL)
1631 PyErr_Clear();
1632 else {
1633 fd = PyLong_AsLong(tmp);
1634 Py_DECREF(tmp);
1635 if (fd < 0 && PyErr_Occurred())
1636 return NULL;
1637 tty = fd == fileno(stdout) && isatty(fd);
1638 }
1639 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 /* If we're interactive, use (GNU) readline */
1642 if (tty) {
1643 PyObject *po;
1644 char *prompt;
1645 char *s;
1646 PyObject *stdin_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001647 char *stdin_encoding_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 PyObject *result;
Victor Stinner02bfdb32011-02-23 12:10:23 +00001649 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1652 if (!stdin_encoding)
1653 /* stdin is a text stream, so it must have an
1654 encoding. */
1655 return NULL;
Victor Stinner306f0102010-05-19 01:06:22 +00001656 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
1657 if (stdin_encoding_str == NULL) {
1658 Py_DECREF(stdin_encoding);
1659 return NULL;
1660 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 tmp = PyObject_CallMethod(fout, "flush", "");
1662 if (tmp == NULL)
1663 PyErr_Clear();
1664 else
1665 Py_DECREF(tmp);
1666 if (promptarg != NULL) {
1667 PyObject *stringpo;
1668 PyObject *stdout_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001669 char *stdout_encoding_str;
1670 stdout_encoding = PyObject_GetAttrString(fout, "encoding");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 if (stdout_encoding == NULL) {
1672 Py_DECREF(stdin_encoding);
1673 return NULL;
1674 }
Victor Stinner306f0102010-05-19 01:06:22 +00001675 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
1676 if (stdout_encoding_str == NULL) {
1677 Py_DECREF(stdin_encoding);
1678 Py_DECREF(stdout_encoding);
1679 return NULL;
1680 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 stringpo = PyObject_Str(promptarg);
1682 if (stringpo == NULL) {
1683 Py_DECREF(stdin_encoding);
1684 Py_DECREF(stdout_encoding);
1685 return NULL;
1686 }
1687 po = PyUnicode_AsEncodedString(stringpo,
Victor Stinner306f0102010-05-19 01:06:22 +00001688 stdout_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 Py_DECREF(stdout_encoding);
1690 Py_DECREF(stringpo);
1691 if (po == NULL) {
1692 Py_DECREF(stdin_encoding);
1693 return NULL;
1694 }
1695 prompt = PyBytes_AsString(po);
1696 if (prompt == NULL) {
1697 Py_DECREF(stdin_encoding);
1698 Py_DECREF(po);
1699 return NULL;
1700 }
1701 }
1702 else {
1703 po = NULL;
1704 prompt = "";
1705 }
1706 s = PyOS_Readline(stdin, stdout, prompt);
1707 Py_XDECREF(po);
1708 if (s == NULL) {
1709 if (!PyErr_Occurred())
1710 PyErr_SetNone(PyExc_KeyboardInterrupt);
1711 Py_DECREF(stdin_encoding);
1712 return NULL;
1713 }
Victor Stinner02bfdb32011-02-23 12:10:23 +00001714
1715 len = strlen(s);
1716 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 PyErr_SetNone(PyExc_EOFError);
1718 result = NULL;
1719 }
Victor Stinner02bfdb32011-02-23 12:10:23 +00001720 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 if (len > PY_SSIZE_T_MAX) {
1722 PyErr_SetString(PyExc_OverflowError,
1723 "input: input too long");
1724 result = NULL;
1725 }
1726 else {
Victor Stinner02bfdb32011-02-23 12:10:23 +00001727 len--; /* strip trailing '\n' */
1728 if (len != 0 && s[len-1] == '\r')
1729 len--; /* strip trailing '\r' */
1730 result = PyUnicode_Decode(s, len, stdin_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 }
1732 }
1733 Py_DECREF(stdin_encoding);
1734 PyMem_FREE(s);
1735 return result;
1736 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 /* Fallback if we're not interactive */
1739 if (promptarg != NULL) {
1740 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1741 return NULL;
1742 }
1743 tmp = PyObject_CallMethod(fout, "flush", "");
1744 if (tmp == NULL)
1745 PyErr_Clear();
1746 else
1747 Py_DECREF(tmp);
1748 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001749}
1750
1751PyDoc_STRVAR(input_doc,
1752"input([prompt]) -> string\n\
1753\n\
1754Read a string from standard input. The trailing newline is stripped.\n\
1755If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1756On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1757is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001758
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001759
Guido van Rossum79f25d91997-04-29 20:08:16 +00001760static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001761builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001764}
1765
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001766PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001767"repr(object) -> string\n\
1768\n\
1769Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001770For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001771
1772
Guido van Rossum79f25d91997-04-29 20:08:16 +00001773static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001774builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 static PyObject *round_str = NULL;
1777 PyObject *ndigits = NULL;
1778 static char *kwlist[] = {"number", "ndigits", 0};
1779 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1782 kwlist, &number, &ndigits))
1783 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 if (Py_TYPE(number)->tp_dict == NULL) {
1786 if (PyType_Ready(Py_TYPE(number)) < 0)
1787 return NULL;
1788 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 if (round_str == NULL) {
1791 round_str = PyUnicode_InternFromString("__round__");
1792 if (round_str == NULL)
1793 return NULL;
1794 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 round = _PyType_Lookup(Py_TYPE(number), round_str);
1797 if (round == NULL) {
1798 PyErr_Format(PyExc_TypeError,
1799 "type %.100s doesn't define __round__ method",
1800 Py_TYPE(number)->tp_name);
1801 return NULL;
1802 }
Alex Martelliae211f92007-08-22 23:21:33 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 if (ndigits == NULL)
1805 return PyObject_CallFunction(round, "O", number);
1806 else
1807 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001808}
1809
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001810PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001811"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001812\n\
1813Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001814This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001815same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001816
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001817
Raymond Hettinger64958a12003-12-17 20:43:33 +00001818static PyObject *
1819builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1822 PyObject *callable;
1823 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1824 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 /* args 1-3 should match listsort in Objects/listobject.c */
1827 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1828 kwlist, &seq, &keyfunc, &reverse))
1829 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 newlist = PySequence_List(seq);
1832 if (newlist == NULL)
1833 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 callable = PyObject_GetAttrString(newlist, "sort");
1836 if (callable == NULL) {
1837 Py_DECREF(newlist);
1838 return NULL;
1839 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 newargs = PyTuple_GetSlice(args, 1, 4);
1842 if (newargs == NULL) {
1843 Py_DECREF(newlist);
1844 Py_DECREF(callable);
1845 return NULL;
1846 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 v = PyObject_Call(callable, newargs, kwds);
1849 Py_DECREF(newargs);
1850 Py_DECREF(callable);
1851 if (v == NULL) {
1852 Py_DECREF(newlist);
1853 return NULL;
1854 }
1855 Py_DECREF(v);
1856 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001857}
1858
1859PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001860"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001861
Guido van Rossum79f25d91997-04-29 20:08:16 +00001862static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001863builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 PyObject *v = NULL;
1866 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1869 return NULL;
1870 if (v == NULL) {
1871 d = PyEval_GetLocals();
1872 if (d == NULL) {
1873 if (!PyErr_Occurred())
1874 PyErr_SetString(PyExc_SystemError,
1875 "vars(): no locals!?");
1876 }
1877 else
1878 Py_INCREF(d);
1879 }
1880 else {
1881 d = PyObject_GetAttrString(v, "__dict__");
1882 if (d == NULL) {
1883 PyErr_SetString(PyExc_TypeError,
1884 "vars() argument must have __dict__ attribute");
1885 return NULL;
1886 }
1887 }
1888 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001889}
1890
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001891PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001892"vars([object]) -> dictionary\n\
1893\n\
1894Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001895With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001896
Alex Martellia70b1912003-04-22 08:12:33 +00001897static PyObject*
1898builtin_sum(PyObject *self, PyObject *args)
1899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 PyObject *seq;
1901 PyObject *result = NULL;
1902 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1905 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 iter = PyObject_GetIter(seq);
1908 if (iter == NULL)
1909 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 if (result == NULL) {
1912 result = PyLong_FromLong(0);
1913 if (result == NULL) {
1914 Py_DECREF(iter);
1915 return NULL;
1916 }
1917 } else {
1918 /* reject string values for 'start' parameter */
1919 if (PyUnicode_Check(result)) {
1920 PyErr_SetString(PyExc_TypeError,
1921 "sum() can't sum strings [use ''.join(seq) instead]");
1922 Py_DECREF(iter);
1923 return NULL;
1924 }
1925 if (PyByteArray_Check(result)) {
1926 PyErr_SetString(PyExc_TypeError,
1927 "sum() can't sum bytes [use b''.join(seq) instead]");
1928 Py_DECREF(iter);
1929 return NULL;
1930 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 Py_INCREF(result);
1933 }
Alex Martellia70b1912003-04-22 08:12:33 +00001934
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001935#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1937 Assumes all inputs are the same type. If the assumption fails, default
1938 to the more general routine.
1939 */
1940 if (PyLong_CheckExact(result)) {
1941 int overflow;
1942 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1943 /* If this already overflowed, don't even enter the loop. */
1944 if (overflow == 0) {
1945 Py_DECREF(result);
1946 result = NULL;
1947 }
1948 while(result == NULL) {
1949 item = PyIter_Next(iter);
1950 if (item == NULL) {
1951 Py_DECREF(iter);
1952 if (PyErr_Occurred())
1953 return NULL;
1954 return PyLong_FromLong(i_result);
1955 }
1956 if (PyLong_CheckExact(item)) {
1957 long b = PyLong_AsLongAndOverflow(item, &overflow);
1958 long x = i_result + b;
1959 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1960 i_result = x;
1961 Py_DECREF(item);
1962 continue;
1963 }
1964 }
1965 /* Either overflowed or is not an int. Restore real objects and process normally */
1966 result = PyLong_FromLong(i_result);
1967 temp = PyNumber_Add(result, item);
1968 Py_DECREF(result);
1969 Py_DECREF(item);
1970 result = temp;
1971 if (result == NULL) {
1972 Py_DECREF(iter);
1973 return NULL;
1974 }
1975 }
1976 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 if (PyFloat_CheckExact(result)) {
1979 double f_result = PyFloat_AS_DOUBLE(result);
1980 Py_DECREF(result);
1981 result = NULL;
1982 while(result == NULL) {
1983 item = PyIter_Next(iter);
1984 if (item == NULL) {
1985 Py_DECREF(iter);
1986 if (PyErr_Occurred())
1987 return NULL;
1988 return PyFloat_FromDouble(f_result);
1989 }
1990 if (PyFloat_CheckExact(item)) {
1991 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1992 f_result += PyFloat_AS_DOUBLE(item);
1993 PyFPE_END_PROTECT(f_result)
1994 Py_DECREF(item);
1995 continue;
1996 }
1997 if (PyLong_CheckExact(item)) {
1998 long value;
1999 int overflow;
2000 value = PyLong_AsLongAndOverflow(item, &overflow);
2001 if (!overflow) {
2002 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2003 f_result += (double)value;
2004 PyFPE_END_PROTECT(f_result)
2005 Py_DECREF(item);
2006 continue;
2007 }
2008 }
2009 result = PyFloat_FromDouble(f_result);
2010 temp = PyNumber_Add(result, item);
2011 Py_DECREF(result);
2012 Py_DECREF(item);
2013 result = temp;
2014 if (result == NULL) {
2015 Py_DECREF(iter);
2016 return NULL;
2017 }
2018 }
2019 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002020#endif
2021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 for(;;) {
2023 item = PyIter_Next(iter);
2024 if (item == NULL) {
2025 /* error, or end-of-sequence */
2026 if (PyErr_Occurred()) {
2027 Py_DECREF(result);
2028 result = NULL;
2029 }
2030 break;
2031 }
2032 /* It's tempting to use PyNumber_InPlaceAdd instead of
2033 PyNumber_Add here, to avoid quadratic running time
2034 when doing 'sum(list_of_lists, [])'. However, this
2035 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 empty = []
2038 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 would change the value of empty. */
2041 temp = PyNumber_Add(result, item);
2042 Py_DECREF(result);
2043 Py_DECREF(item);
2044 result = temp;
2045 if (result == NULL)
2046 break;
2047 }
2048 Py_DECREF(iter);
2049 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002050}
2051
2052PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002053"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002054\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002055Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2056of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002057empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002058
2059
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002060static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002061builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 PyObject *inst;
2064 PyObject *cls;
2065 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2068 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 retval = PyObject_IsInstance(inst, cls);
2071 if (retval < 0)
2072 return NULL;
2073 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002074}
2075
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002076PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002077"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002078\n\
2079Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002080With a type as second argument, return whether that is the object's type.\n\
2081The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002082isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002083
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002084
2085static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002086builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 PyObject *derived;
2089 PyObject *cls;
2090 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2093 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 retval = PyObject_IsSubclass(derived, cls);
2096 if (retval < 0)
2097 return NULL;
2098 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002099}
2100
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002101PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002102"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002103\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002104Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2105When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2106is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002107
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002108
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002109typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 PyObject_HEAD
2111 Py_ssize_t tuplesize;
2112 PyObject *ittuple; /* tuple of iterators */
2113 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002114} zipobject;
2115
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002116static PyObject *
2117zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 zipobject *lz;
2120 Py_ssize_t i;
2121 PyObject *ittuple; /* tuple of iterators */
2122 PyObject *result;
2123 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2126 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 /* args must be a tuple */
2129 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 /* obtain iterators */
2132 ittuple = PyTuple_New(tuplesize);
2133 if (ittuple == NULL)
2134 return NULL;
2135 for (i=0; i < tuplesize; ++i) {
2136 PyObject *item = PyTuple_GET_ITEM(args, i);
2137 PyObject *it = PyObject_GetIter(item);
2138 if (it == NULL) {
2139 if (PyErr_ExceptionMatches(PyExc_TypeError))
2140 PyErr_Format(PyExc_TypeError,
2141 "zip argument #%zd must support iteration",
2142 i+1);
2143 Py_DECREF(ittuple);
2144 return NULL;
2145 }
2146 PyTuple_SET_ITEM(ittuple, i, it);
2147 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 /* create a result holder */
2150 result = PyTuple_New(tuplesize);
2151 if (result == NULL) {
2152 Py_DECREF(ittuple);
2153 return NULL;
2154 }
2155 for (i=0 ; i < tuplesize ; i++) {
2156 Py_INCREF(Py_None);
2157 PyTuple_SET_ITEM(result, i, Py_None);
2158 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 /* create zipobject structure */
2161 lz = (zipobject *)type->tp_alloc(type, 0);
2162 if (lz == NULL) {
2163 Py_DECREF(ittuple);
2164 Py_DECREF(result);
2165 return NULL;
2166 }
2167 lz->ittuple = ittuple;
2168 lz->tuplesize = tuplesize;
2169 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002172}
2173
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002174static void
2175zip_dealloc(zipobject *lz)
2176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 PyObject_GC_UnTrack(lz);
2178 Py_XDECREF(lz->ittuple);
2179 Py_XDECREF(lz->result);
2180 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002181}
2182
2183static int
2184zip_traverse(zipobject *lz, visitproc visit, void *arg)
2185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 Py_VISIT(lz->ittuple);
2187 Py_VISIT(lz->result);
2188 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002189}
2190
2191static PyObject *
2192zip_next(zipobject *lz)
2193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 Py_ssize_t i;
2195 Py_ssize_t tuplesize = lz->tuplesize;
2196 PyObject *result = lz->result;
2197 PyObject *it;
2198 PyObject *item;
2199 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 if (tuplesize == 0)
2202 return NULL;
2203 if (Py_REFCNT(result) == 1) {
2204 Py_INCREF(result);
2205 for (i=0 ; i < tuplesize ; i++) {
2206 it = PyTuple_GET_ITEM(lz->ittuple, i);
2207 item = (*Py_TYPE(it)->tp_iternext)(it);
2208 if (item == NULL) {
2209 Py_DECREF(result);
2210 return NULL;
2211 }
2212 olditem = PyTuple_GET_ITEM(result, i);
2213 PyTuple_SET_ITEM(result, i, item);
2214 Py_DECREF(olditem);
2215 }
2216 } else {
2217 result = PyTuple_New(tuplesize);
2218 if (result == NULL)
2219 return NULL;
2220 for (i=0 ; i < tuplesize ; i++) {
2221 it = PyTuple_GET_ITEM(lz->ittuple, i);
2222 item = (*Py_TYPE(it)->tp_iternext)(it);
2223 if (item == NULL) {
2224 Py_DECREF(result);
2225 return NULL;
2226 }
2227 PyTuple_SET_ITEM(result, i, item);
2228 }
2229 }
2230 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002231}
Barry Warsawbd599b52000-08-03 15:45:29 +00002232
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002233PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002234"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002235\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002236Return a zip object whose .__next__() method returns a tuple where\n\
2237the i-th element comes from the i-th iterable argument. The .__next__()\n\
2238method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002239is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002240
2241PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2243 "zip", /* tp_name */
2244 sizeof(zipobject), /* tp_basicsize */
2245 0, /* tp_itemsize */
2246 /* methods */
2247 (destructor)zip_dealloc, /* tp_dealloc */
2248 0, /* tp_print */
2249 0, /* tp_getattr */
2250 0, /* tp_setattr */
2251 0, /* tp_reserved */
2252 0, /* tp_repr */
2253 0, /* tp_as_number */
2254 0, /* tp_as_sequence */
2255 0, /* tp_as_mapping */
2256 0, /* tp_hash */
2257 0, /* tp_call */
2258 0, /* tp_str */
2259 PyObject_GenericGetAttr, /* tp_getattro */
2260 0, /* tp_setattro */
2261 0, /* tp_as_buffer */
2262 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2263 Py_TPFLAGS_BASETYPE, /* tp_flags */
2264 zip_doc, /* tp_doc */
2265 (traverseproc)zip_traverse, /* tp_traverse */
2266 0, /* tp_clear */
2267 0, /* tp_richcompare */
2268 0, /* tp_weaklistoffset */
2269 PyObject_SelfIter, /* tp_iter */
2270 (iternextfunc)zip_next, /* tp_iternext */
2271 0, /* tp_methods */
2272 0, /* tp_members */
2273 0, /* tp_getset */
2274 0, /* tp_base */
2275 0, /* tp_dict */
2276 0, /* tp_descr_get */
2277 0, /* tp_descr_set */
2278 0, /* tp_dictoffset */
2279 0, /* tp_init */
2280 PyType_GenericAlloc, /* tp_alloc */
2281 zip_new, /* tp_new */
2282 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002283};
Barry Warsawbd599b52000-08-03 15:45:29 +00002284
2285
Guido van Rossum79f25d91997-04-29 20:08:16 +00002286static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 {"__build_class__", (PyCFunction)builtin___build_class__,
2288 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2289 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2290 {"abs", builtin_abs, METH_O, abs_doc},
2291 {"all", builtin_all, METH_O, all_doc},
2292 {"any", builtin_any, METH_O, any_doc},
2293 {"ascii", builtin_ascii, METH_O, ascii_doc},
2294 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002295 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2297 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2298 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2299 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2300 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2301 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2302 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2303 {"format", builtin_format, METH_VARARGS, format_doc},
2304 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2305 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2306 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2307 {"hash", builtin_hash, METH_O, hash_doc},
2308 {"hex", builtin_hex, METH_O, hex_doc},
2309 {"id", builtin_id, METH_O, id_doc},
2310 {"input", builtin_input, METH_VARARGS, input_doc},
2311 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2312 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2313 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2314 {"len", builtin_len, METH_O, len_doc},
2315 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2316 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2317 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2318 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2319 {"oct", builtin_oct, METH_O, oct_doc},
2320 {"ord", builtin_ord, METH_O, ord_doc},
2321 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2322 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2323 {"repr", builtin_repr, METH_O, repr_doc},
2324 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2325 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2326 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2327 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2328 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2329 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002330};
2331
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002332PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002333"Built-in functions, exceptions, and other objects.\n\
2334\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002335Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002336
Martin v. Löwis1a214512008-06-11 05:26:20 +00002337static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 PyModuleDef_HEAD_INIT,
2339 "builtins",
2340 builtin_doc,
2341 -1, /* multiple "initialization" just copies the module dict. */
2342 builtin_methods,
2343 NULL,
2344 NULL,
2345 NULL,
2346 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002347};
2348
2349
Guido van Rossum25ce5661997-08-02 03:10:38 +00002350PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002351_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 PyObject *mod, *dict, *debug;
2354 mod = PyModule_Create(&builtinsmodule);
2355 if (mod == NULL)
2356 return NULL;
2357 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002358
Tim Peters7571a0f2003-03-23 17:52:28 +00002359#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 /* "builtins" exposes a number of statically allocated objects
2361 * that, before this code was added in 2.3, never showed up in
2362 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2363 * result, programs leaking references to None and False (etc)
2364 * couldn't be diagnosed by examining sys.getobjects(0).
2365 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002366#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2367#else
2368#define ADD_TO_ALL(OBJECT) (void)0
2369#endif
2370
Tim Peters4b7625e2001-09-13 21:37:17 +00002371#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2373 return NULL; \
2374 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 SETBUILTIN("None", Py_None);
2377 SETBUILTIN("Ellipsis", Py_Ellipsis);
2378 SETBUILTIN("NotImplemented", Py_NotImplemented);
2379 SETBUILTIN("False", Py_False);
2380 SETBUILTIN("True", Py_True);
2381 SETBUILTIN("bool", &PyBool_Type);
2382 SETBUILTIN("memoryview", &PyMemoryView_Type);
2383 SETBUILTIN("bytearray", &PyByteArray_Type);
2384 SETBUILTIN("bytes", &PyBytes_Type);
2385 SETBUILTIN("classmethod", &PyClassMethod_Type);
2386 SETBUILTIN("complex", &PyComplex_Type);
2387 SETBUILTIN("dict", &PyDict_Type);
2388 SETBUILTIN("enumerate", &PyEnum_Type);
2389 SETBUILTIN("filter", &PyFilter_Type);
2390 SETBUILTIN("float", &PyFloat_Type);
2391 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2392 SETBUILTIN("property", &PyProperty_Type);
2393 SETBUILTIN("int", &PyLong_Type);
2394 SETBUILTIN("list", &PyList_Type);
2395 SETBUILTIN("map", &PyMap_Type);
2396 SETBUILTIN("object", &PyBaseObject_Type);
2397 SETBUILTIN("range", &PyRange_Type);
2398 SETBUILTIN("reversed", &PyReversed_Type);
2399 SETBUILTIN("set", &PySet_Type);
2400 SETBUILTIN("slice", &PySlice_Type);
2401 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2402 SETBUILTIN("str", &PyUnicode_Type);
2403 SETBUILTIN("super", &PySuper_Type);
2404 SETBUILTIN("tuple", &PyTuple_Type);
2405 SETBUILTIN("type", &PyType_Type);
2406 SETBUILTIN("zip", &PyZip_Type);
2407 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2408 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2409 Py_XDECREF(debug);
2410 return NULL;
2411 }
2412 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002415#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002416#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002417}