blob: 9c50b88da8dfb0db98b6248d020fbd1c418dd6a3 [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 Hammond26cffde2001-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 Hammond26cffde2001-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 Hammond26cffde2001-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 Hammond26cffde2001-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;
40 Py_ssize_t nargs, nbases;
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;
65 nbases = nargs - 2;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 if (kwds == NULL) {
68 meta = NULL;
69 mkw = NULL;
70 }
71 else {
72 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
73 if (mkw == NULL) {
74 Py_DECREF(bases);
75 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000076 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 meta = PyDict_GetItemString(mkw, "metaclass");
78 if (meta != NULL) {
79 Py_INCREF(meta);
80 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
81 Py_DECREF(meta);
82 Py_DECREF(mkw);
83 Py_DECREF(bases);
84 return NULL;
85 }
Nick Coghlande31b192011-10-23 22:04:16 +100086 /* metaclass is explicitly given, check if it's indeed a class */
87 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 }
89 }
90 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +100091 /* if there are no bases, use type: */
92 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +100094 }
95 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 else {
97 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
98 meta = (PyObject *) (base0->ob_type);
99 }
100 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000101 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 }
Nick Coghlande31b192011-10-23 22:04:16 +1000103 if (isclass) {
104 /* meta is really a class, so check for a more derived
105 metaclass, or possible metaclass conflicts: */
106 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
107 bases);
108 if (winner == NULL) {
109 Py_DECREF(meta);
110 Py_XDECREF(mkw);
111 Py_DECREF(bases);
112 return NULL;
113 }
114 if (winner != meta) {
115 Py_DECREF(meta);
116 meta = winner;
117 Py_INCREF(meta);
118 }
119 }
120 /* else: meta is not a class, so we cannot do the metaclass
121 calculation, so we will use the explicitly given object as it is */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 prep = PyObject_GetAttrString(meta, "__prepare__");
123 if (prep == NULL) {
124 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
125 PyErr_Clear();
126 ns = PyDict_New();
127 }
128 else {
129 Py_DECREF(meta);
130 Py_XDECREF(mkw);
131 Py_DECREF(bases);
132 return NULL;
133 }
134 }
135 else {
136 PyObject *pargs = PyTuple_Pack(2, name, bases);
137 if (pargs == NULL) {
138 Py_DECREF(prep);
139 Py_DECREF(meta);
140 Py_XDECREF(mkw);
141 Py_DECREF(bases);
142 return NULL;
143 }
144 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
145 Py_DECREF(pargs);
146 Py_DECREF(prep);
147 }
148 if (ns == NULL) {
149 Py_DECREF(meta);
150 Py_XDECREF(mkw);
151 Py_DECREF(bases);
152 return NULL;
153 }
154 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
155 if (cell != NULL) {
156 PyObject *margs;
157 margs = PyTuple_Pack(3, name, bases, ns);
158 if (margs != NULL) {
159 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
160 Py_DECREF(margs);
161 }
162 if (cls != NULL && PyCell_Check(cell)) {
163 Py_INCREF(cls);
164 PyCell_SET(cell, cls);
165 }
166 Py_DECREF(cell);
167 }
168 Py_DECREF(ns);
169 Py_DECREF(meta);
170 Py_XDECREF(mkw);
171 Py_DECREF(bases);
172 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000173}
174
175PyDoc_STRVAR(build_class_doc,
176"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
177\n\
178Internal helper function used by the class statement.");
179
180static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000181builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
184 "level", 0};
185 char *name;
186 PyObject *globals = NULL;
187 PyObject *locals = NULL;
188 PyObject *fromlist = NULL;
189 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
192 kwlist, &name, &globals, &locals, &fromlist, &level))
193 return NULL;
194 return PyImport_ImportModuleLevel(name, globals, locals,
195 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000196}
197
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000198PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000199"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000200\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000201Import a module. Because this function is meant for use by the Python\n\
202interpreter and not for general use it is better to use\n\
203importlib.import_module() to programmatically import a module.\n\
204\n\
205The globals argument is only used to determine the context;\n\
206they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000207should be a list of names to emulate ``from name import ...'', or an\n\
208empty list to emulate ``import name''.\n\
209When importing a module from a package, note that __import__('A.B', ...)\n\
210returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000211fromlist is not empty. Level is used to determine whether to perform \n\
212absolute or relative imports. -1 is the original strategy of attempting\n\
213both absolute and relative imports, 0 is absolute, a positive number\n\
214is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000215
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000216
Guido van Rossum79f25d91997-04-29 20:08:16 +0000217static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000218builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000221}
222
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000223PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000224"abs(number) -> number\n\
225\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000226Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000227
Raymond Hettinger96229b12005-03-11 06:49:40 +0000228static PyObject *
229builtin_all(PyObject *self, PyObject *v)
230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 PyObject *it, *item;
232 PyObject *(*iternext)(PyObject *);
233 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 it = PyObject_GetIter(v);
236 if (it == NULL)
237 return NULL;
238 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 for (;;) {
241 item = iternext(it);
242 if (item == NULL)
243 break;
244 cmp = PyObject_IsTrue(item);
245 Py_DECREF(item);
246 if (cmp < 0) {
247 Py_DECREF(it);
248 return NULL;
249 }
250 if (cmp == 0) {
251 Py_DECREF(it);
252 Py_RETURN_FALSE;
253 }
254 }
255 Py_DECREF(it);
256 if (PyErr_Occurred()) {
257 if (PyErr_ExceptionMatches(PyExc_StopIteration))
258 PyErr_Clear();
259 else
260 return NULL;
261 }
262 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000263}
264
265PyDoc_STRVAR(all_doc,
266"all(iterable) -> bool\n\
267\n\
268Return True if bool(x) is True for all values x in the iterable.");
269
270static PyObject *
271builtin_any(PyObject *self, PyObject *v)
272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 PyObject *it, *item;
274 PyObject *(*iternext)(PyObject *);
275 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 it = PyObject_GetIter(v);
278 if (it == NULL)
279 return NULL;
280 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 for (;;) {
283 item = iternext(it);
284 if (item == NULL)
285 break;
286 cmp = PyObject_IsTrue(item);
287 Py_DECREF(item);
288 if (cmp < 0) {
289 Py_DECREF(it);
290 return NULL;
291 }
292 if (cmp == 1) {
293 Py_DECREF(it);
294 Py_RETURN_TRUE;
295 }
296 }
297 Py_DECREF(it);
298 if (PyErr_Occurred()) {
299 if (PyErr_ExceptionMatches(PyExc_StopIteration))
300 PyErr_Clear();
301 else
302 return NULL;
303 }
304 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000305}
306
307PyDoc_STRVAR(any_doc,
308"any(iterable) -> bool\n\
309\n\
310Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000311
Georg Brandl559e5d72008-06-11 18:37:52 +0000312static PyObject *
313builtin_ascii(PyObject *self, PyObject *v)
314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000316}
317
318PyDoc_STRVAR(ascii_doc,
319"ascii(object) -> string\n\
320\n\
321As repr(), return a string containing a printable representation of an\n\
322object, but escape the non-ASCII characters in the string returned by\n\
323repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
324to that returned by repr() in Python 2.");
325
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000326
Guido van Rossum79f25d91997-04-29 20:08:16 +0000327static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000328builtin_bin(PyObject *self, PyObject *v)
329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000331}
332
333PyDoc_STRVAR(bin_doc,
334"bin(number) -> string\n\
335\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -0400336Return the binary representation of an integer.");
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000337
338
Antoine Pitroue71362d2010-11-27 22:00:11 +0000339static PyObject *
340builtin_callable(PyObject *self, PyObject *v)
341{
342 return PyBool_FromLong((long)PyCallable_Check(v));
343}
344
345PyDoc_STRVAR(callable_doc,
346"callable(object) -> bool\n\
347\n\
348Return whether the object is callable (i.e., some kind of function).\n\
349Note that classes are callable, as are instances of classes with a\n\
350__call__() method.");
351
352
Raymond Hettinger17301e92008-03-13 00:19:26 +0000353typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 PyObject_HEAD
355 PyObject *func;
356 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000357} filterobject;
358
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000359static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000360filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 PyObject *func, *seq;
363 PyObject *it;
364 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
367 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
370 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 /* Get iterator. */
373 it = PyObject_GetIter(seq);
374 if (it == NULL)
375 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 /* create filterobject structure */
378 lz = (filterobject *)type->tp_alloc(type, 0);
379 if (lz == NULL) {
380 Py_DECREF(it);
381 return NULL;
382 }
383 Py_INCREF(func);
384 lz->func = func;
385 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000388}
389
390static void
391filter_dealloc(filterobject *lz)
392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 PyObject_GC_UnTrack(lz);
394 Py_XDECREF(lz->func);
395 Py_XDECREF(lz->it);
396 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000397}
398
399static int
400filter_traverse(filterobject *lz, visitproc visit, void *arg)
401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 Py_VISIT(lz->it);
403 Py_VISIT(lz->func);
404 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000405}
406
407static PyObject *
408filter_next(filterobject *lz)
409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 PyObject *item;
411 PyObject *it = lz->it;
412 long ok;
413 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 iternext = *Py_TYPE(it)->tp_iternext;
416 for (;;) {
417 item = iternext(it);
418 if (item == NULL)
419 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
422 ok = PyObject_IsTrue(item);
423 } else {
424 PyObject *good;
425 good = PyObject_CallFunctionObjArgs(lz->func,
426 item, NULL);
427 if (good == NULL) {
428 Py_DECREF(item);
429 return NULL;
430 }
431 ok = PyObject_IsTrue(good);
432 Py_DECREF(good);
433 }
434 if (ok)
435 return item;
436 Py_DECREF(item);
437 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000438}
439
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000440PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000441"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000442\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000443Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000444is true. If function is None, return the items that are true.");
445
446PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 PyVarObject_HEAD_INIT(&PyType_Type, 0)
448 "filter", /* tp_name */
449 sizeof(filterobject), /* tp_basicsize */
450 0, /* tp_itemsize */
451 /* methods */
452 (destructor)filter_dealloc, /* tp_dealloc */
453 0, /* tp_print */
454 0, /* tp_getattr */
455 0, /* tp_setattr */
456 0, /* tp_reserved */
457 0, /* tp_repr */
458 0, /* tp_as_number */
459 0, /* tp_as_sequence */
460 0, /* tp_as_mapping */
461 0, /* tp_hash */
462 0, /* tp_call */
463 0, /* tp_str */
464 PyObject_GenericGetAttr, /* tp_getattro */
465 0, /* tp_setattro */
466 0, /* tp_as_buffer */
467 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
468 Py_TPFLAGS_BASETYPE, /* tp_flags */
469 filter_doc, /* tp_doc */
470 (traverseproc)filter_traverse, /* tp_traverse */
471 0, /* tp_clear */
472 0, /* tp_richcompare */
473 0, /* tp_weaklistoffset */
474 PyObject_SelfIter, /* tp_iter */
475 (iternextfunc)filter_next, /* tp_iternext */
476 0, /* tp_methods */
477 0, /* tp_members */
478 0, /* tp_getset */
479 0, /* tp_base */
480 0, /* tp_dict */
481 0, /* tp_descr_get */
482 0, /* tp_descr_set */
483 0, /* tp_dictoffset */
484 0, /* tp_init */
485 PyType_GenericAlloc, /* tp_alloc */
486 filter_new, /* tp_new */
487 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000488};
489
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000490
Eric Smith8c663262007-08-25 02:26:07 +0000491static PyObject *
492builtin_format(PyObject *self, PyObject *args)
493{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000494 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000495 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000496
Eric Smith8fd3eba2008-02-17 19:48:00 +0000497 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000499
Eric Smith8fd3eba2008-02-17 19:48:00 +0000500 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000501}
502
Eric Smith8c663262007-08-25 02:26:07 +0000503PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000504"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000505\n\
Eric Smith81936692007-08-31 01:14:01 +0000506Returns value.__format__(format_spec)\n\
507format_spec defaults to \"\"");
508
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000509static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000510builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 if (!PyArg_ParseTuple(args, "i:chr", &x))
515 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000518}
519
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000520PyDoc_VAR(chr_doc) = PyDoc_STR(
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000521"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000522\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000523Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000524)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000525#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000526PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000527"\nIf 0x10000 <= i, a surrogate pair is returned."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000528)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000529#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000530;
Guido van Rossum09095f32000-03-10 23:00:52 +0000531
532
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000533static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000534source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 char *str;
537 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 if (PyUnicode_Check(cmd)) {
540 cf->cf_flags |= PyCF_IGNORE_COOKIE;
541 cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL);
542 if (cmd == NULL)
543 return NULL;
544 }
545 else if (!PyObject_CheckReadBuffer(cmd)) {
546 PyErr_Format(PyExc_TypeError,
547 "%s() arg 1 must be a %s object",
548 funcname, what);
549 return NULL;
550 }
551 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
552 return NULL;
553 }
554 if (strlen(str) != size) {
555 PyErr_SetString(PyExc_TypeError,
556 "source code string cannot contain null bytes");
557 return NULL;
558 }
559 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000560}
561
Guido van Rossum79f25d91997-04-29 20:08:16 +0000562static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000563builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 char *str;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000566 PyObject *filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 char *filename;
568 char *startstr;
569 int mode = -1;
570 int dont_inherit = 0;
571 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000572 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 int is_ast;
574 PyCompilerFlags cf;
575 PyObject *cmd;
576 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000577 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000579 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000580
Georg Brandl8334fd92010-12-04 10:26:46 +0000581 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000582 &cmd,
583 PyUnicode_FSConverter, &filename_obj,
584 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000585 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000587
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000588 filename = PyBytes_AS_STRING(filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 if (supplied_flags &
592 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
593 {
594 PyErr_SetString(PyExc_ValueError,
595 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000596 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 }
598 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000599
Georg Brandl8334fd92010-12-04 10:26:46 +0000600 if (optimize < -1 || optimize > 2) {
601 PyErr_SetString(PyExc_ValueError,
602 "compile(): invalid optimize value");
603 goto error;
604 }
605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (!dont_inherit) {
607 PyEval_MergeCompilerFlags(&cf);
608 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 if (strcmp(startstr, "exec") == 0)
611 mode = 0;
612 else if (strcmp(startstr, "eval") == 0)
613 mode = 1;
614 else if (strcmp(startstr, "single") == 0)
615 mode = 2;
616 else {
617 PyErr_SetString(PyExc_ValueError,
618 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000619 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 is_ast = PyAST_Check(cmd);
623 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000624 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 if (supplied_flags & PyCF_ONLY_AST) {
627 Py_INCREF(cmd);
628 result = cmd;
629 }
630 else {
631 PyArena *arena;
632 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 arena = PyArena_New();
635 mod = PyAST_obj2mod(cmd, arena, mode);
636 if (mod == NULL) {
637 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000638 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 }
Georg Brandl8334fd92010-12-04 10:26:46 +0000640 result = (PyObject*)PyAST_CompileEx(mod, filename,
641 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 PyArena_Free(arena);
643 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000644 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
648 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000649 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000650
Georg Brandl8334fd92010-12-04 10:26:46 +0000651 result = Py_CompileStringExFlags(str, filename, start[mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000652 goto finally;
653
654error:
655 result = NULL;
656finally:
657 Py_DECREF(filename_obj);
658 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000659}
660
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000661PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000662"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000663\n\
664Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000665into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000666The filename will be used for run-time error messages.\n\
667The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000668single (interactive) statement, or 'eval' to compile an expression.\n\
669The flags argument, if present, controls which future statements influence\n\
670the compilation of the code.\n\
671The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
672the effects of any future statements in effect in the code calling\n\
673compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000674in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000675
Guido van Rossum79f25d91997-04-29 20:08:16 +0000676static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000677builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
682 return NULL;
683 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000684}
685
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000686PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000687"dir([object]) -> list of strings\n"
688"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000689"If called without an argument, return the names in the current scope.\n"
690"Else, return an alphabetized list of names comprising (some of) the attributes\n"
691"of the given object, and of attributes reachable from it.\n"
692"If the object supplies a method named __dir__, it will be used; otherwise\n"
693"the default dir() logic is used and returns:\n"
694" for a module object: the module's attributes.\n"
695" for a class object: its attributes, and recursively the attributes\n"
696" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000697" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000698" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000699
Guido van Rossum79f25d91997-04-29 20:08:16 +0000700static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000701builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
706 return NULL;
707 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000708}
709
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000710PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000711"divmod(x, y) -> (div, mod)\n\
712\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000713Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000714
715
Guido van Rossum79f25d91997-04-29 20:08:16 +0000716static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000717builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 PyObject *cmd, *result, *tmp = NULL;
720 PyObject *globals = Py_None, *locals = Py_None;
721 char *str;
722 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
725 return NULL;
726 if (locals != Py_None && !PyMapping_Check(locals)) {
727 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
728 return NULL;
729 }
730 if (globals != Py_None && !PyDict_Check(globals)) {
731 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
732 "globals must be a real dict; try eval(expr, {}, mapping)"
733 : "globals must be a dict");
734 return NULL;
735 }
736 if (globals == Py_None) {
737 globals = PyEval_GetGlobals();
738 if (locals == Py_None)
739 locals = PyEval_GetLocals();
740 }
741 else if (locals == Py_None)
742 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 if (globals == NULL || locals == NULL) {
745 PyErr_SetString(PyExc_TypeError,
746 "eval must be given globals and locals "
747 "when called without a frame");
748 return NULL;
749 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
752 if (PyDict_SetItemString(globals, "__builtins__",
753 PyEval_GetBuiltins()) != 0)
754 return NULL;
755 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 if (PyCode_Check(cmd)) {
758 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
759 PyErr_SetString(PyExc_TypeError,
760 "code object passed to eval() may not contain free variables");
761 return NULL;
762 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000763 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
767 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
768 if (str == NULL)
769 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 while (*str == ' ' || *str == '\t')
772 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 (void)PyEval_MergeCompilerFlags(&cf);
775 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
776 Py_XDECREF(tmp);
777 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000778}
779
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000780PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000781"eval(source[, globals[, locals]]) -> value\n\
782\n\
783Evaluate the source in the context of globals and locals.\n\
784The source may be a string representing a Python expression\n\
785or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000786The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000787defaulting to the current globals and locals.\n\
788If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000789
Georg Brandl7cae87c2006-09-06 06:51:57 +0000790static PyObject *
791builtin_exec(PyObject *self, PyObject *args)
792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 PyObject *v;
794 PyObject *prog, *globals = Py_None, *locals = Py_None;
795 int plain = 0;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
798 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 if (globals == Py_None) {
801 globals = PyEval_GetGlobals();
802 if (locals == Py_None) {
803 locals = PyEval_GetLocals();
804 plain = 1;
805 }
806 if (!globals || !locals) {
807 PyErr_SetString(PyExc_SystemError,
808 "globals and locals cannot be NULL");
809 return NULL;
810 }
811 }
812 else if (locals == Py_None)
813 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 if (!PyDict_Check(globals)) {
816 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
817 globals->ob_type->tp_name);
818 return NULL;
819 }
820 if (!PyMapping_Check(locals)) {
821 PyErr_Format(PyExc_TypeError,
822 "arg 3 must be a mapping or None, not %.100s",
823 locals->ob_type->tp_name);
824 return NULL;
825 }
826 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
827 if (PyDict_SetItemString(globals, "__builtins__",
828 PyEval_GetBuiltins()) != 0)
829 return NULL;
830 }
831
832 if (PyCode_Check(prog)) {
833 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
834 PyErr_SetString(PyExc_TypeError,
835 "code object passed to exec() may not "
836 "contain free variables");
837 return NULL;
838 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000839 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 }
841 else {
842 char *str;
843 PyCompilerFlags cf;
844 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
845 str = source_as_string(prog, "exec",
846 "string, bytes or code", &cf);
847 if (str == NULL)
848 return NULL;
849 if (PyEval_MergeCompilerFlags(&cf))
850 v = PyRun_StringFlags(str, Py_file_input, globals,
851 locals, &cf);
852 else
853 v = PyRun_String(str, Py_file_input, globals, locals);
854 }
855 if (v == NULL)
856 return NULL;
857 Py_DECREF(v);
858 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000859}
860
861PyDoc_STRVAR(exec_doc,
862"exec(object[, globals[, locals]])\n\
863\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000864Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000865object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000866The globals and locals are dictionaries, defaulting to the current\n\
867globals and locals. If only globals is given, locals defaults to it.");
868
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000869
Guido van Rossum79f25d91997-04-29 20:08:16 +0000870static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000871builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 PyObject *v, *result, *dflt = NULL;
874 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
877 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 if (!PyUnicode_Check(name)) {
880 PyErr_SetString(PyExc_TypeError,
881 "getattr(): attribute name must be string");
882 return NULL;
883 }
884 result = PyObject_GetAttr(v, name);
885 if (result == NULL && dflt != NULL &&
886 PyErr_ExceptionMatches(PyExc_AttributeError))
887 {
888 PyErr_Clear();
889 Py_INCREF(dflt);
890 result = dflt;
891 }
892 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000893}
894
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000895PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000896"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000897\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000898Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
899When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000900exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000901
902
Guido van Rossum79f25d91997-04-29 20:08:16 +0000903static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000904builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 d = PyEval_GetGlobals();
909 Py_XINCREF(d);
910 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000911}
912
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000913PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000914"globals() -> dictionary\n\
915\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000916Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000917
918
Guido van Rossum79f25d91997-04-29 20:08:16 +0000919static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000920builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 PyObject *v;
923 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
926 return NULL;
927 if (!PyUnicode_Check(name)) {
928 PyErr_SetString(PyExc_TypeError,
929 "hasattr(): attribute name must be string");
930 return NULL;
931 }
932 v = PyObject_GetAttr(v, name);
933 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000934 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000936 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000938 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 }
940 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000941 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000942}
943
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000944PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000945"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000946\n\
947Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000948(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000949
950
Guido van Rossum79f25d91997-04-29 20:08:16 +0000951static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000952builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000955}
956
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000957PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000958"id(object) -> integer\n\
959\n\
960Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000961simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000962
963
Raymond Hettingera6c60372008-03-13 01:26:19 +0000964/* map object ************************************************************/
965
966typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 PyObject_HEAD
968 PyObject *iters;
969 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000970} mapobject;
971
Guido van Rossum79f25d91997-04-29 20:08:16 +0000972static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000973map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 PyObject *it, *iters, *func;
976 mapobject *lz;
977 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
980 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 numargs = PyTuple_Size(args);
983 if (numargs < 2) {
984 PyErr_SetString(PyExc_TypeError,
985 "map() must have at least two arguments.");
986 return NULL;
987 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 iters = PyTuple_New(numargs-1);
990 if (iters == NULL)
991 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 for (i=1 ; i<numargs ; i++) {
994 /* Get iterator. */
995 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
996 if (it == NULL) {
997 Py_DECREF(iters);
998 return NULL;
999 }
1000 PyTuple_SET_ITEM(iters, i-1, it);
1001 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 /* create mapobject structure */
1004 lz = (mapobject *)type->tp_alloc(type, 0);
1005 if (lz == NULL) {
1006 Py_DECREF(iters);
1007 return NULL;
1008 }
1009 lz->iters = iters;
1010 func = PyTuple_GET_ITEM(args, 0);
1011 Py_INCREF(func);
1012 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001015}
1016
1017static void
1018map_dealloc(mapobject *lz)
1019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 PyObject_GC_UnTrack(lz);
1021 Py_XDECREF(lz->iters);
1022 Py_XDECREF(lz->func);
1023 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001024}
1025
1026static int
1027map_traverse(mapobject *lz, visitproc visit, void *arg)
1028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 Py_VISIT(lz->iters);
1030 Py_VISIT(lz->func);
1031 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001032}
1033
1034static PyObject *
1035map_next(mapobject *lz)
1036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 PyObject *val;
1038 PyObject *argtuple;
1039 PyObject *result;
1040 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 numargs = PyTuple_Size(lz->iters);
1043 argtuple = PyTuple_New(numargs);
1044 if (argtuple == NULL)
1045 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 for (i=0 ; i<numargs ; i++) {
1048 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1049 if (val == NULL) {
1050 Py_DECREF(argtuple);
1051 return NULL;
1052 }
1053 PyTuple_SET_ITEM(argtuple, i, val);
1054 }
1055 result = PyObject_Call(lz->func, argtuple, NULL);
1056 Py_DECREF(argtuple);
1057 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001058}
1059
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001060PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001061"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001062\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001063Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001065
Raymond Hettingera6c60372008-03-13 01:26:19 +00001066PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1068 "map", /* tp_name */
1069 sizeof(mapobject), /* tp_basicsize */
1070 0, /* tp_itemsize */
1071 /* methods */
1072 (destructor)map_dealloc, /* tp_dealloc */
1073 0, /* tp_print */
1074 0, /* tp_getattr */
1075 0, /* tp_setattr */
1076 0, /* tp_reserved */
1077 0, /* tp_repr */
1078 0, /* tp_as_number */
1079 0, /* tp_as_sequence */
1080 0, /* tp_as_mapping */
1081 0, /* tp_hash */
1082 0, /* tp_call */
1083 0, /* tp_str */
1084 PyObject_GenericGetAttr, /* tp_getattro */
1085 0, /* tp_setattro */
1086 0, /* tp_as_buffer */
1087 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1088 Py_TPFLAGS_BASETYPE, /* tp_flags */
1089 map_doc, /* tp_doc */
1090 (traverseproc)map_traverse, /* tp_traverse */
1091 0, /* tp_clear */
1092 0, /* tp_richcompare */
1093 0, /* tp_weaklistoffset */
1094 PyObject_SelfIter, /* tp_iter */
1095 (iternextfunc)map_next, /* tp_iternext */
1096 0, /* tp_methods */
1097 0, /* tp_members */
1098 0, /* tp_getset */
1099 0, /* tp_base */
1100 0, /* tp_dict */
1101 0, /* tp_descr_get */
1102 0, /* tp_descr_set */
1103 0, /* tp_dictoffset */
1104 0, /* tp_init */
1105 PyType_GenericAlloc, /* tp_alloc */
1106 map_new, /* tp_new */
1107 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001108};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001109
Guido van Rossum79f25d91997-04-29 20:08:16 +00001110static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001111builtin_next(PyObject *self, PyObject *args)
1112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 PyObject *it, *res;
1114 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1117 return NULL;
1118 if (!PyIter_Check(it)) {
1119 PyErr_Format(PyExc_TypeError,
1120 "%.200s object is not an iterator",
1121 it->ob_type->tp_name);
1122 return NULL;
1123 }
1124
1125 res = (*it->ob_type->tp_iternext)(it);
1126 if (res != NULL) {
1127 return res;
1128 } else if (def != NULL) {
1129 if (PyErr_Occurred()) {
1130 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1131 return NULL;
1132 PyErr_Clear();
1133 }
1134 Py_INCREF(def);
1135 return def;
1136 } else if (PyErr_Occurred()) {
1137 return NULL;
1138 } else {
1139 PyErr_SetNone(PyExc_StopIteration);
1140 return NULL;
1141 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001142}
1143
1144PyDoc_STRVAR(next_doc,
1145"next(iterator[, default])\n\
1146\n\
1147Return the next item from the iterator. If default is given and the iterator\n\
1148is exhausted, it is returned instead of raising StopIteration.");
1149
1150
1151static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001152builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 PyObject *v;
1155 PyObject *name;
1156 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1159 return NULL;
1160 if (PyObject_SetAttr(v, name, value) != 0)
1161 return NULL;
1162 Py_INCREF(Py_None);
1163 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001164}
1165
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001166PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001167"setattr(object, name, value)\n\
1168\n\
1169Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001170``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001171
1172
Guido van Rossum79f25d91997-04-29 20:08:16 +00001173static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001174builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 PyObject *v;
1177 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1180 return NULL;
1181 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1182 return NULL;
1183 Py_INCREF(Py_None);
1184 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001185}
1186
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001187PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001188"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001189\n\
1190Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001191``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001192
1193
Guido van Rossum79f25d91997-04-29 20:08:16 +00001194static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001195builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001196{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001197 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 x = PyObject_Hash(v);
1200 if (x == -1)
1201 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001202 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001203}
1204
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001205PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001206"hash(object) -> integer\n\
1207\n\
1208Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001209the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001210
1211
Guido van Rossum79f25d91997-04-29 20:08:16 +00001212static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001213builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001216}
1217
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001218PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001219"hex(number) -> string\n\
1220\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001221Return the hexadecimal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001222
1223
Guido van Rossum79f25d91997-04-29 20:08:16 +00001224static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001225builtin_iter(PyObject *self, PyObject *args)
1226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1230 return NULL;
1231 if (w == NULL)
1232 return PyObject_GetIter(v);
1233 if (!PyCallable_Check(v)) {
1234 PyErr_SetString(PyExc_TypeError,
1235 "iter(v, w): v must be callable");
1236 return NULL;
1237 }
1238 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001239}
1240
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001241PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001242"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001243iter(callable, sentinel) -> iterator\n\
1244\n\
1245Get an iterator from an object. In the first form, the argument must\n\
1246supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001247In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001248
1249
1250static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001251builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 res = PyObject_Size(v);
1256 if (res < 0 && PyErr_Occurred())
1257 return NULL;
1258 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001259}
1260
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001261PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001262"len(object) -> integer\n\
1263\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001264Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001265
1266
Guido van Rossum79f25d91997-04-29 20:08:16 +00001267static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001268builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 d = PyEval_GetLocals();
1273 Py_XINCREF(d);
1274 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001275}
1276
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001277PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001278"locals() -> dictionary\n\
1279\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001280Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001281
1282
Guido van Rossum79f25d91997-04-29 20:08:16 +00001283static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001284min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1287 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 if (PyTuple_Size(args) > 1)
1290 v = args;
1291 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1292 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1295 keyfunc = PyDict_GetItemString(kwds, "key");
1296 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1297 PyErr_Format(PyExc_TypeError,
1298 "%s() got an unexpected keyword argument", name);
1299 return NULL;
1300 }
1301 Py_INCREF(keyfunc);
1302 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 it = PyObject_GetIter(v);
1305 if (it == NULL) {
1306 Py_XDECREF(keyfunc);
1307 return NULL;
1308 }
Tim Petersc3074532001-05-03 07:00:32 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 maxitem = NULL; /* the result */
1311 maxval = NULL; /* the value associated with the result */
1312 while (( item = PyIter_Next(it) )) {
1313 /* get the value from the key function */
1314 if (keyfunc != NULL) {
1315 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1316 if (val == NULL)
1317 goto Fail_it_item;
1318 }
1319 /* no key function; the value is the item */
1320 else {
1321 val = item;
1322 Py_INCREF(val);
1323 }
Tim Petersc3074532001-05-03 07:00:32 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 /* maximum value and item are unset; set them */
1326 if (maxval == NULL) {
1327 maxitem = item;
1328 maxval = val;
1329 }
1330 /* maximum value and item are set; update them as necessary */
1331 else {
1332 int cmp = PyObject_RichCompareBool(val, maxval, op);
1333 if (cmp < 0)
1334 goto Fail_it_item_and_val;
1335 else if (cmp > 0) {
1336 Py_DECREF(maxval);
1337 Py_DECREF(maxitem);
1338 maxval = val;
1339 maxitem = item;
1340 }
1341 else {
1342 Py_DECREF(item);
1343 Py_DECREF(val);
1344 }
1345 }
1346 }
1347 if (PyErr_Occurred())
1348 goto Fail_it;
1349 if (maxval == NULL) {
1350 PyErr_Format(PyExc_ValueError,
1351 "%s() arg is an empty sequence", name);
1352 assert(maxitem == NULL);
1353 }
1354 else
1355 Py_DECREF(maxval);
1356 Py_DECREF(it);
1357 Py_XDECREF(keyfunc);
1358 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001359
1360Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001362Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001364Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 Py_XDECREF(maxval);
1366 Py_XDECREF(maxitem);
1367 Py_DECREF(it);
1368 Py_XDECREF(keyfunc);
1369 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001370}
1371
Guido van Rossum79f25d91997-04-29 20:08:16 +00001372static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001373builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001376}
1377
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001378PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001379"min(iterable[, key=func]) -> value\n\
1380min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001381\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001382With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001383With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001384
1385
Guido van Rossum79f25d91997-04-29 20:08:16 +00001386static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001387builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001390}
1391
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001392PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001393"max(iterable[, key=func]) -> value\n\
1394max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001395\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001396With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001397With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001398
1399
Guido van Rossum79f25d91997-04-29 20:08:16 +00001400static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001401builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001404}
1405
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001406PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001407"oct(number) -> string\n\
1408\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001409Return the octal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001410
1411
Guido van Rossum79f25d91997-04-29 20:08:16 +00001412static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001413builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 long ord;
1416 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 if (PyBytes_Check(obj)) {
1419 size = PyBytes_GET_SIZE(obj);
1420 if (size == 1) {
1421 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1422 return PyLong_FromLong(ord);
1423 }
1424 }
1425 else if (PyUnicode_Check(obj)) {
1426 size = PyUnicode_GET_SIZE(obj);
1427 if (size == 1) {
1428 ord = (long)*PyUnicode_AS_UNICODE(obj);
1429 return PyLong_FromLong(ord);
1430 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001431#ifndef Py_UNICODE_WIDE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 if (size == 2) {
1433 /* Decode a valid surrogate pair */
1434 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1435 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1436 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1437 0xDC00 <= c1 && c1 <= 0xDFFF) {
1438 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1439 0x00010000);
1440 return PyLong_FromLong(ord);
1441 }
1442 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001443#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 }
1445 else if (PyByteArray_Check(obj)) {
1446 /* XXX Hopefully this is temporary */
1447 size = PyByteArray_GET_SIZE(obj);
1448 if (size == 1) {
1449 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1450 return PyLong_FromLong(ord);
1451 }
1452 }
1453 else {
1454 PyErr_Format(PyExc_TypeError,
1455 "ord() expected string of length 1, but " \
1456 "%.200s found", obj->ob_type->tp_name);
1457 return NULL;
1458 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 PyErr_Format(PyExc_TypeError,
1461 "ord() expected a character, "
1462 "but string of length %zd found",
1463 size);
1464 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001465}
1466
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001467PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001468"ord(c) -> integer\n\
1469\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001470Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001471)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001472#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001473PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001474"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001475)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001476#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001477;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001478
1479
Guido van Rossum79f25d91997-04-29 20:08:16 +00001480static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001481builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1486 return NULL;
1487 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001488}
1489
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001490PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001491"pow(x, y[, z]) -> number\n\
1492\n\
1493With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001494equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001495
1496
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001497
Guido van Rossum34343512006-11-30 22:13:52 +00001498static PyObject *
1499builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 static char *kwlist[] = {"sep", "end", "file", 0};
1502 static PyObject *dummy_args;
1503 PyObject *sep = NULL, *end = NULL, *file = NULL;
1504 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 if (dummy_args == NULL) {
1507 if (!(dummy_args = PyTuple_New(0)))
1508 return NULL;
1509 }
1510 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1511 kwlist, &sep, &end, &file))
1512 return NULL;
1513 if (file == NULL || file == Py_None) {
1514 file = PySys_GetObject("stdout");
1515 /* sys.stdout may be None when FILE* stdout isn't connected */
1516 if (file == Py_None)
1517 Py_RETURN_NONE;
1518 }
Guido van Rossum34343512006-11-30 22:13:52 +00001519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 if (sep == Py_None) {
1521 sep = NULL;
1522 }
1523 else if (sep && !PyUnicode_Check(sep)) {
1524 PyErr_Format(PyExc_TypeError,
1525 "sep must be None or a string, not %.200s",
1526 sep->ob_type->tp_name);
1527 return NULL;
1528 }
1529 if (end == Py_None) {
1530 end = NULL;
1531 }
1532 else if (end && !PyUnicode_Check(end)) {
1533 PyErr_Format(PyExc_TypeError,
1534 "end must be None or a string, not %.200s",
1535 end->ob_type->tp_name);
1536 return NULL;
1537 }
Guido van Rossum34343512006-11-30 22:13:52 +00001538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 for (i = 0; i < PyTuple_Size(args); i++) {
1540 if (i > 0) {
1541 if (sep == NULL)
1542 err = PyFile_WriteString(" ", file);
1543 else
1544 err = PyFile_WriteObject(sep, file,
1545 Py_PRINT_RAW);
1546 if (err)
1547 return NULL;
1548 }
1549 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1550 Py_PRINT_RAW);
1551 if (err)
1552 return NULL;
1553 }
Guido van Rossum34343512006-11-30 22:13:52 +00001554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 if (end == NULL)
1556 err = PyFile_WriteString("\n", file);
1557 else
1558 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1559 if (err)
1560 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001563}
1564
1565PyDoc_STRVAR(print_doc,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001566"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001567\n\
1568Prints the values to a stream, or to sys.stdout by default.\n\
1569Optional keyword arguments:\n\
1570file: a file-like object (stream); defaults to the current sys.stdout.\n\
1571sep: string inserted between values, default a space.\n\
1572end: string appended after the last value, default a newline.");
1573
1574
Guido van Rossuma88a0332007-02-26 16:59:55 +00001575static PyObject *
1576builtin_input(PyObject *self, PyObject *args)
1577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 PyObject *promptarg = NULL;
1579 PyObject *fin = PySys_GetObject("stdin");
1580 PyObject *fout = PySys_GetObject("stdout");
1581 PyObject *ferr = PySys_GetObject("stderr");
1582 PyObject *tmp;
1583 long fd;
1584 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 /* Parse arguments */
1587 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1588 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 /* Check that stdin/out/err are intact */
1591 if (fin == NULL || fin == Py_None) {
1592 PyErr_SetString(PyExc_RuntimeError,
1593 "input(): lost sys.stdin");
1594 return NULL;
1595 }
1596 if (fout == NULL || fout == Py_None) {
1597 PyErr_SetString(PyExc_RuntimeError,
1598 "input(): lost sys.stdout");
1599 return NULL;
1600 }
1601 if (ferr == NULL || ferr == Py_None) {
1602 PyErr_SetString(PyExc_RuntimeError,
1603 "input(): lost sys.stderr");
1604 return NULL;
1605 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 /* First of all, flush stderr */
1608 tmp = PyObject_CallMethod(ferr, "flush", "");
1609 if (tmp == NULL)
1610 PyErr_Clear();
1611 else
1612 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 /* We should only use (GNU) readline if Python's sys.stdin and
1615 sys.stdout are the same as C's stdin and stdout, because we
1616 need to pass it those. */
1617 tmp = PyObject_CallMethod(fin, "fileno", "");
1618 if (tmp == NULL) {
1619 PyErr_Clear();
1620 tty = 0;
1621 }
1622 else {
1623 fd = PyLong_AsLong(tmp);
1624 Py_DECREF(tmp);
1625 if (fd < 0 && PyErr_Occurred())
1626 return NULL;
1627 tty = fd == fileno(stdin) && isatty(fd);
1628 }
1629 if (tty) {
1630 tmp = PyObject_CallMethod(fout, "fileno", "");
1631 if (tmp == NULL)
1632 PyErr_Clear();
1633 else {
1634 fd = PyLong_AsLong(tmp);
1635 Py_DECREF(tmp);
1636 if (fd < 0 && PyErr_Occurred())
1637 return NULL;
1638 tty = fd == fileno(stdout) && isatty(fd);
1639 }
1640 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 /* If we're interactive, use (GNU) readline */
1643 if (tty) {
1644 PyObject *po;
1645 char *prompt;
1646 char *s;
1647 PyObject *stdin_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001648 char *stdin_encoding_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 PyObject *result;
Victor Stinner02bfdb32011-02-23 12:10:23 +00001650 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1653 if (!stdin_encoding)
1654 /* stdin is a text stream, so it must have an
1655 encoding. */
1656 return NULL;
Victor Stinner306f0102010-05-19 01:06:22 +00001657 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
1658 if (stdin_encoding_str == NULL) {
1659 Py_DECREF(stdin_encoding);
1660 return NULL;
1661 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 tmp = PyObject_CallMethod(fout, "flush", "");
1663 if (tmp == NULL)
1664 PyErr_Clear();
1665 else
1666 Py_DECREF(tmp);
1667 if (promptarg != NULL) {
1668 PyObject *stringpo;
1669 PyObject *stdout_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001670 char *stdout_encoding_str;
1671 stdout_encoding = PyObject_GetAttrString(fout, "encoding");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 if (stdout_encoding == NULL) {
1673 Py_DECREF(stdin_encoding);
1674 return NULL;
1675 }
Victor Stinner306f0102010-05-19 01:06:22 +00001676 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
1677 if (stdout_encoding_str == NULL) {
1678 Py_DECREF(stdin_encoding);
1679 Py_DECREF(stdout_encoding);
1680 return NULL;
1681 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 stringpo = PyObject_Str(promptarg);
1683 if (stringpo == NULL) {
1684 Py_DECREF(stdin_encoding);
1685 Py_DECREF(stdout_encoding);
1686 return NULL;
1687 }
1688 po = PyUnicode_AsEncodedString(stringpo,
Victor Stinner306f0102010-05-19 01:06:22 +00001689 stdout_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 Py_DECREF(stdout_encoding);
1691 Py_DECREF(stringpo);
1692 if (po == NULL) {
1693 Py_DECREF(stdin_encoding);
1694 return NULL;
1695 }
1696 prompt = PyBytes_AsString(po);
1697 if (prompt == NULL) {
1698 Py_DECREF(stdin_encoding);
1699 Py_DECREF(po);
1700 return NULL;
1701 }
1702 }
1703 else {
1704 po = NULL;
1705 prompt = "";
1706 }
1707 s = PyOS_Readline(stdin, stdout, prompt);
1708 Py_XDECREF(po);
1709 if (s == NULL) {
1710 if (!PyErr_Occurred())
1711 PyErr_SetNone(PyExc_KeyboardInterrupt);
1712 Py_DECREF(stdin_encoding);
1713 return NULL;
1714 }
Victor Stinner02bfdb32011-02-23 12:10:23 +00001715
1716 len = strlen(s);
1717 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 PyErr_SetNone(PyExc_EOFError);
1719 result = NULL;
1720 }
Victor Stinner02bfdb32011-02-23 12:10:23 +00001721 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 if (len > PY_SSIZE_T_MAX) {
1723 PyErr_SetString(PyExc_OverflowError,
1724 "input: input too long");
1725 result = NULL;
1726 }
1727 else {
Victor Stinner02bfdb32011-02-23 12:10:23 +00001728 len--; /* strip trailing '\n' */
1729 if (len != 0 && s[len-1] == '\r')
1730 len--; /* strip trailing '\r' */
1731 result = PyUnicode_Decode(s, len, stdin_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 }
1733 }
1734 Py_DECREF(stdin_encoding);
1735 PyMem_FREE(s);
1736 return result;
1737 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 /* Fallback if we're not interactive */
1740 if (promptarg != NULL) {
1741 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1742 return NULL;
1743 }
1744 tmp = PyObject_CallMethod(fout, "flush", "");
1745 if (tmp == NULL)
1746 PyErr_Clear();
1747 else
1748 Py_DECREF(tmp);
1749 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001750}
1751
1752PyDoc_STRVAR(input_doc,
1753"input([prompt]) -> string\n\
1754\n\
1755Read a string from standard input. The trailing newline is stripped.\n\
1756If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1757On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1758is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001759
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001760
Guido van Rossum79f25d91997-04-29 20:08:16 +00001761static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001762builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001765}
1766
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001767PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001768"repr(object) -> string\n\
1769\n\
1770Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001771For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001772
1773
Guido van Rossum79f25d91997-04-29 20:08:16 +00001774static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001775builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 static PyObject *round_str = NULL;
1778 PyObject *ndigits = NULL;
1779 static char *kwlist[] = {"number", "ndigits", 0};
1780 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1783 kwlist, &number, &ndigits))
1784 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 if (Py_TYPE(number)->tp_dict == NULL) {
1787 if (PyType_Ready(Py_TYPE(number)) < 0)
1788 return NULL;
1789 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 if (round_str == NULL) {
1792 round_str = PyUnicode_InternFromString("__round__");
1793 if (round_str == NULL)
1794 return NULL;
1795 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 round = _PyType_Lookup(Py_TYPE(number), round_str);
1798 if (round == NULL) {
1799 PyErr_Format(PyExc_TypeError,
1800 "type %.100s doesn't define __round__ method",
1801 Py_TYPE(number)->tp_name);
1802 return NULL;
1803 }
Alex Martelliae211f92007-08-22 23:21:33 +00001804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 if (ndigits == NULL)
1806 return PyObject_CallFunction(round, "O", number);
1807 else
1808 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001809}
1810
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001811PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001812"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001813\n\
1814Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001815This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001816same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001817
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001818
Raymond Hettinger64958a12003-12-17 20:43:33 +00001819static PyObject *
1820builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1823 PyObject *callable;
1824 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1825 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 /* args 1-3 should match listsort in Objects/listobject.c */
1828 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1829 kwlist, &seq, &keyfunc, &reverse))
1830 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 newlist = PySequence_List(seq);
1833 if (newlist == NULL)
1834 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 callable = PyObject_GetAttrString(newlist, "sort");
1837 if (callable == NULL) {
1838 Py_DECREF(newlist);
1839 return NULL;
1840 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 newargs = PyTuple_GetSlice(args, 1, 4);
1843 if (newargs == NULL) {
1844 Py_DECREF(newlist);
1845 Py_DECREF(callable);
1846 return NULL;
1847 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 v = PyObject_Call(callable, newargs, kwds);
1850 Py_DECREF(newargs);
1851 Py_DECREF(callable);
1852 if (v == NULL) {
1853 Py_DECREF(newlist);
1854 return NULL;
1855 }
1856 Py_DECREF(v);
1857 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001858}
1859
1860PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001861"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001862
Guido van Rossum79f25d91997-04-29 20:08:16 +00001863static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001864builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 PyObject *v = NULL;
1867 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1870 return NULL;
1871 if (v == NULL) {
1872 d = PyEval_GetLocals();
1873 if (d == NULL) {
1874 if (!PyErr_Occurred())
1875 PyErr_SetString(PyExc_SystemError,
1876 "vars(): no locals!?");
1877 }
1878 else
1879 Py_INCREF(d);
1880 }
1881 else {
1882 d = PyObject_GetAttrString(v, "__dict__");
1883 if (d == NULL) {
1884 PyErr_SetString(PyExc_TypeError,
1885 "vars() argument must have __dict__ attribute");
1886 return NULL;
1887 }
1888 }
1889 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001890}
1891
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001892PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001893"vars([object]) -> dictionary\n\
1894\n\
1895Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001896With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001897
Alex Martellia70b1912003-04-22 08:12:33 +00001898static PyObject*
1899builtin_sum(PyObject *self, PyObject *args)
1900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 PyObject *seq;
1902 PyObject *result = NULL;
1903 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1906 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 iter = PyObject_GetIter(seq);
1909 if (iter == NULL)
1910 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 if (result == NULL) {
1913 result = PyLong_FromLong(0);
1914 if (result == NULL) {
1915 Py_DECREF(iter);
1916 return NULL;
1917 }
1918 } else {
1919 /* reject string values for 'start' parameter */
1920 if (PyUnicode_Check(result)) {
1921 PyErr_SetString(PyExc_TypeError,
1922 "sum() can't sum strings [use ''.join(seq) instead]");
1923 Py_DECREF(iter);
1924 return NULL;
1925 }
1926 if (PyByteArray_Check(result)) {
1927 PyErr_SetString(PyExc_TypeError,
1928 "sum() can't sum bytes [use b''.join(seq) instead]");
1929 Py_DECREF(iter);
1930 return NULL;
1931 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 Py_INCREF(result);
1934 }
Alex Martellia70b1912003-04-22 08:12:33 +00001935
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001936#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1938 Assumes all inputs are the same type. If the assumption fails, default
1939 to the more general routine.
1940 */
1941 if (PyLong_CheckExact(result)) {
1942 int overflow;
1943 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1944 /* If this already overflowed, don't even enter the loop. */
1945 if (overflow == 0) {
1946 Py_DECREF(result);
1947 result = NULL;
1948 }
1949 while(result == NULL) {
1950 item = PyIter_Next(iter);
1951 if (item == NULL) {
1952 Py_DECREF(iter);
1953 if (PyErr_Occurred())
1954 return NULL;
1955 return PyLong_FromLong(i_result);
1956 }
1957 if (PyLong_CheckExact(item)) {
1958 long b = PyLong_AsLongAndOverflow(item, &overflow);
1959 long x = i_result + b;
1960 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1961 i_result = x;
1962 Py_DECREF(item);
1963 continue;
1964 }
1965 }
1966 /* Either overflowed or is not an int. Restore real objects and process normally */
1967 result = PyLong_FromLong(i_result);
1968 temp = PyNumber_Add(result, item);
1969 Py_DECREF(result);
1970 Py_DECREF(item);
1971 result = temp;
1972 if (result == NULL) {
1973 Py_DECREF(iter);
1974 return NULL;
1975 }
1976 }
1977 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 if (PyFloat_CheckExact(result)) {
1980 double f_result = PyFloat_AS_DOUBLE(result);
1981 Py_DECREF(result);
1982 result = NULL;
1983 while(result == NULL) {
1984 item = PyIter_Next(iter);
1985 if (item == NULL) {
1986 Py_DECREF(iter);
1987 if (PyErr_Occurred())
1988 return NULL;
1989 return PyFloat_FromDouble(f_result);
1990 }
1991 if (PyFloat_CheckExact(item)) {
1992 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1993 f_result += PyFloat_AS_DOUBLE(item);
1994 PyFPE_END_PROTECT(f_result)
1995 Py_DECREF(item);
1996 continue;
1997 }
1998 if (PyLong_CheckExact(item)) {
1999 long value;
2000 int overflow;
2001 value = PyLong_AsLongAndOverflow(item, &overflow);
2002 if (!overflow) {
2003 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2004 f_result += (double)value;
2005 PyFPE_END_PROTECT(f_result)
2006 Py_DECREF(item);
2007 continue;
2008 }
2009 }
2010 result = PyFloat_FromDouble(f_result);
2011 temp = PyNumber_Add(result, item);
2012 Py_DECREF(result);
2013 Py_DECREF(item);
2014 result = temp;
2015 if (result == NULL) {
2016 Py_DECREF(iter);
2017 return NULL;
2018 }
2019 }
2020 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002021#endif
2022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 for(;;) {
2024 item = PyIter_Next(iter);
2025 if (item == NULL) {
2026 /* error, or end-of-sequence */
2027 if (PyErr_Occurred()) {
2028 Py_DECREF(result);
2029 result = NULL;
2030 }
2031 break;
2032 }
2033 /* It's tempting to use PyNumber_InPlaceAdd instead of
2034 PyNumber_Add here, to avoid quadratic running time
2035 when doing 'sum(list_of_lists, [])'. However, this
2036 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 empty = []
2039 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 would change the value of empty. */
2042 temp = PyNumber_Add(result, item);
2043 Py_DECREF(result);
2044 Py_DECREF(item);
2045 result = temp;
2046 if (result == NULL)
2047 break;
2048 }
2049 Py_DECREF(iter);
2050 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002051}
2052
2053PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002054"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002055\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002056Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2057of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002058empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002059
2060
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002061static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002062builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 PyObject *inst;
2065 PyObject *cls;
2066 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2069 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 retval = PyObject_IsInstance(inst, cls);
2072 if (retval < 0)
2073 return NULL;
2074 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002075}
2076
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002077PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002078"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002079\n\
2080Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002081With a type as second argument, return whether that is the object's type.\n\
2082The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002083isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002084
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002085
2086static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002087builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 PyObject *derived;
2090 PyObject *cls;
2091 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2094 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 retval = PyObject_IsSubclass(derived, cls);
2097 if (retval < 0)
2098 return NULL;
2099 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002100}
2101
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002102PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002103"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002104\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002105Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2106When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2107is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002108
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002109
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002110typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 PyObject_HEAD
2112 Py_ssize_t tuplesize;
2113 PyObject *ittuple; /* tuple of iterators */
2114 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002115} zipobject;
2116
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002117static PyObject *
2118zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 zipobject *lz;
2121 Py_ssize_t i;
2122 PyObject *ittuple; /* tuple of iterators */
2123 PyObject *result;
2124 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2127 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 /* args must be a tuple */
2130 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 /* obtain iterators */
2133 ittuple = PyTuple_New(tuplesize);
2134 if (ittuple == NULL)
2135 return NULL;
2136 for (i=0; i < tuplesize; ++i) {
2137 PyObject *item = PyTuple_GET_ITEM(args, i);
2138 PyObject *it = PyObject_GetIter(item);
2139 if (it == NULL) {
2140 if (PyErr_ExceptionMatches(PyExc_TypeError))
2141 PyErr_Format(PyExc_TypeError,
2142 "zip argument #%zd must support iteration",
2143 i+1);
2144 Py_DECREF(ittuple);
2145 return NULL;
2146 }
2147 PyTuple_SET_ITEM(ittuple, i, it);
2148 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 /* create a result holder */
2151 result = PyTuple_New(tuplesize);
2152 if (result == NULL) {
2153 Py_DECREF(ittuple);
2154 return NULL;
2155 }
2156 for (i=0 ; i < tuplesize ; i++) {
2157 Py_INCREF(Py_None);
2158 PyTuple_SET_ITEM(result, i, Py_None);
2159 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 /* create zipobject structure */
2162 lz = (zipobject *)type->tp_alloc(type, 0);
2163 if (lz == NULL) {
2164 Py_DECREF(ittuple);
2165 Py_DECREF(result);
2166 return NULL;
2167 }
2168 lz->ittuple = ittuple;
2169 lz->tuplesize = tuplesize;
2170 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002173}
2174
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002175static void
2176zip_dealloc(zipobject *lz)
2177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 PyObject_GC_UnTrack(lz);
2179 Py_XDECREF(lz->ittuple);
2180 Py_XDECREF(lz->result);
2181 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002182}
2183
2184static int
2185zip_traverse(zipobject *lz, visitproc visit, void *arg)
2186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 Py_VISIT(lz->ittuple);
2188 Py_VISIT(lz->result);
2189 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002190}
2191
2192static PyObject *
2193zip_next(zipobject *lz)
2194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 Py_ssize_t i;
2196 Py_ssize_t tuplesize = lz->tuplesize;
2197 PyObject *result = lz->result;
2198 PyObject *it;
2199 PyObject *item;
2200 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 if (tuplesize == 0)
2203 return NULL;
2204 if (Py_REFCNT(result) == 1) {
2205 Py_INCREF(result);
2206 for (i=0 ; i < tuplesize ; i++) {
2207 it = PyTuple_GET_ITEM(lz->ittuple, i);
2208 item = (*Py_TYPE(it)->tp_iternext)(it);
2209 if (item == NULL) {
2210 Py_DECREF(result);
2211 return NULL;
2212 }
2213 olditem = PyTuple_GET_ITEM(result, i);
2214 PyTuple_SET_ITEM(result, i, item);
2215 Py_DECREF(olditem);
2216 }
2217 } else {
2218 result = PyTuple_New(tuplesize);
2219 if (result == NULL)
2220 return NULL;
2221 for (i=0 ; i < tuplesize ; i++) {
2222 it = PyTuple_GET_ITEM(lz->ittuple, i);
2223 item = (*Py_TYPE(it)->tp_iternext)(it);
2224 if (item == NULL) {
2225 Py_DECREF(result);
2226 return NULL;
2227 }
2228 PyTuple_SET_ITEM(result, i, item);
2229 }
2230 }
2231 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002232}
Barry Warsawbd599b52000-08-03 15:45:29 +00002233
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002234PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002235"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002236\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002237Return a zip object whose .__next__() method returns a tuple where\n\
2238the i-th element comes from the i-th iterable argument. The .__next__()\n\
2239method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002240is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002241
2242PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2244 "zip", /* tp_name */
2245 sizeof(zipobject), /* tp_basicsize */
2246 0, /* tp_itemsize */
2247 /* methods */
2248 (destructor)zip_dealloc, /* tp_dealloc */
2249 0, /* tp_print */
2250 0, /* tp_getattr */
2251 0, /* tp_setattr */
2252 0, /* tp_reserved */
2253 0, /* tp_repr */
2254 0, /* tp_as_number */
2255 0, /* tp_as_sequence */
2256 0, /* tp_as_mapping */
2257 0, /* tp_hash */
2258 0, /* tp_call */
2259 0, /* tp_str */
2260 PyObject_GenericGetAttr, /* tp_getattro */
2261 0, /* tp_setattro */
2262 0, /* tp_as_buffer */
2263 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2264 Py_TPFLAGS_BASETYPE, /* tp_flags */
2265 zip_doc, /* tp_doc */
2266 (traverseproc)zip_traverse, /* tp_traverse */
2267 0, /* tp_clear */
2268 0, /* tp_richcompare */
2269 0, /* tp_weaklistoffset */
2270 PyObject_SelfIter, /* tp_iter */
2271 (iternextfunc)zip_next, /* tp_iternext */
2272 0, /* tp_methods */
2273 0, /* tp_members */
2274 0, /* tp_getset */
2275 0, /* tp_base */
2276 0, /* tp_dict */
2277 0, /* tp_descr_get */
2278 0, /* tp_descr_set */
2279 0, /* tp_dictoffset */
2280 0, /* tp_init */
2281 PyType_GenericAlloc, /* tp_alloc */
2282 zip_new, /* tp_new */
2283 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002284};
Barry Warsawbd599b52000-08-03 15:45:29 +00002285
2286
Guido van Rossum79f25d91997-04-29 20:08:16 +00002287static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 {"__build_class__", (PyCFunction)builtin___build_class__,
2289 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2290 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2291 {"abs", builtin_abs, METH_O, abs_doc},
2292 {"all", builtin_all, METH_O, all_doc},
2293 {"any", builtin_any, METH_O, any_doc},
2294 {"ascii", builtin_ascii, METH_O, ascii_doc},
2295 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002296 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2298 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2299 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2300 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2301 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2302 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2303 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2304 {"format", builtin_format, METH_VARARGS, format_doc},
2305 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2306 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2307 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2308 {"hash", builtin_hash, METH_O, hash_doc},
2309 {"hex", builtin_hex, METH_O, hex_doc},
2310 {"id", builtin_id, METH_O, id_doc},
2311 {"input", builtin_input, METH_VARARGS, input_doc},
2312 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2313 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2314 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2315 {"len", builtin_len, METH_O, len_doc},
2316 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2317 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2318 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2319 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2320 {"oct", builtin_oct, METH_O, oct_doc},
2321 {"ord", builtin_ord, METH_O, ord_doc},
2322 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2323 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2324 {"repr", builtin_repr, METH_O, repr_doc},
2325 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2326 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2327 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2328 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2329 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2330 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002331};
2332
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002333PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002334"Built-in functions, exceptions, and other objects.\n\
2335\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002336Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002337
Martin v. Löwis1a214512008-06-11 05:26:20 +00002338static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 PyModuleDef_HEAD_INIT,
2340 "builtins",
2341 builtin_doc,
2342 -1, /* multiple "initialization" just copies the module dict. */
2343 builtin_methods,
2344 NULL,
2345 NULL,
2346 NULL,
2347 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002348};
2349
2350
Guido van Rossum25ce5661997-08-02 03:10:38 +00002351PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002352_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 PyObject *mod, *dict, *debug;
2355 mod = PyModule_Create(&builtinsmodule);
2356 if (mod == NULL)
2357 return NULL;
2358 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002359
Tim Peters7571a0f2003-03-23 17:52:28 +00002360#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 /* "builtins" exposes a number of statically allocated objects
2362 * that, before this code was added in 2.3, never showed up in
2363 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2364 * result, programs leaking references to None and False (etc)
2365 * couldn't be diagnosed by examining sys.getobjects(0).
2366 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002367#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2368#else
2369#define ADD_TO_ALL(OBJECT) (void)0
2370#endif
2371
Tim Peters4b7625e2001-09-13 21:37:17 +00002372#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2374 return NULL; \
2375 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 SETBUILTIN("None", Py_None);
2378 SETBUILTIN("Ellipsis", Py_Ellipsis);
2379 SETBUILTIN("NotImplemented", Py_NotImplemented);
2380 SETBUILTIN("False", Py_False);
2381 SETBUILTIN("True", Py_True);
2382 SETBUILTIN("bool", &PyBool_Type);
2383 SETBUILTIN("memoryview", &PyMemoryView_Type);
2384 SETBUILTIN("bytearray", &PyByteArray_Type);
2385 SETBUILTIN("bytes", &PyBytes_Type);
2386 SETBUILTIN("classmethod", &PyClassMethod_Type);
2387 SETBUILTIN("complex", &PyComplex_Type);
2388 SETBUILTIN("dict", &PyDict_Type);
2389 SETBUILTIN("enumerate", &PyEnum_Type);
2390 SETBUILTIN("filter", &PyFilter_Type);
2391 SETBUILTIN("float", &PyFloat_Type);
2392 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2393 SETBUILTIN("property", &PyProperty_Type);
2394 SETBUILTIN("int", &PyLong_Type);
2395 SETBUILTIN("list", &PyList_Type);
2396 SETBUILTIN("map", &PyMap_Type);
2397 SETBUILTIN("object", &PyBaseObject_Type);
2398 SETBUILTIN("range", &PyRange_Type);
2399 SETBUILTIN("reversed", &PyReversed_Type);
2400 SETBUILTIN("set", &PySet_Type);
2401 SETBUILTIN("slice", &PySlice_Type);
2402 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2403 SETBUILTIN("str", &PyUnicode_Type);
2404 SETBUILTIN("super", &PySuper_Type);
2405 SETBUILTIN("tuple", &PyTuple_Type);
2406 SETBUILTIN("type", &PyType_Type);
2407 SETBUILTIN("zip", &PyZip_Type);
2408 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2409 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2410 Py_XDECREF(debug);
2411 return NULL;
2412 }
2413 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002416#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002417#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002418}