blob: 3074e4cb63cc5c97f709b5b6c3031328616968cb [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008
Guido van Rossum6bf62da1997-04-11 20:37:35 +00009#include <ctype.h>
10
Victor Stinnerb744ba12010-05-15 12:27:16 +000011#ifdef HAVE_LANGINFO_H
12#include <langinfo.h> /* CODESET */
13#endif
14
Mark Hammond26cffde42001-05-14 12:17:34 +000015/* The default encoding used by the platform file system APIs
16 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000017
18 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
19 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000020*/
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000021#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Mark Hammond26cffde42001-05-14 12:17:34 +000022const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000023int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000024#elif defined(__APPLE__)
25const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerb744ba12010-05-15 12:27:16 +000027#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
28const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int Py_HasFileSystemDefaultEncoding = 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +000030#else
31const char *Py_FileSystemDefaultEncoding = "utf-8";
32int Py_HasFileSystemDefaultEncoding = 1;
Mark Hammond26cffde42001-05-14 12:17:34 +000033#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000034
Guido van Rossum79f25d91997-04-29 20:08:16 +000035static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000036builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
37{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000038 PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell;
39 PyObject *cls = NULL;
Brett Cannonb94767f2011-02-22 20:15:44 +000040 Py_ssize_t nargs;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 assert(args != NULL);
43 if (!PyTuple_Check(args)) {
44 PyErr_SetString(PyExc_TypeError,
45 "__build_class__: args is not a tuple");
46 return NULL;
47 }
48 nargs = PyTuple_GET_SIZE(args);
49 if (nargs < 2) {
50 PyErr_SetString(PyExc_TypeError,
51 "__build_class__: not enough arguments");
52 return NULL;
53 }
54 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
55 name = PyTuple_GET_ITEM(args, 1);
56 if (!PyUnicode_Check(name)) {
57 PyErr_SetString(PyExc_TypeError,
58 "__build_class__: name is not a string");
59 return NULL;
60 }
61 bases = PyTuple_GetSlice(args, 2, nargs);
62 if (bases == NULL)
63 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 if (kwds == NULL) {
66 meta = NULL;
67 mkw = NULL;
68 }
69 else {
70 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
71 if (mkw == NULL) {
72 Py_DECREF(bases);
73 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000074 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 meta = PyDict_GetItemString(mkw, "metaclass");
76 if (meta != NULL) {
77 Py_INCREF(meta);
78 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
79 Py_DECREF(meta);
80 Py_DECREF(mkw);
81 Py_DECREF(bases);
82 return NULL;
83 }
84 }
85 }
86 if (meta == NULL) {
87 if (PyTuple_GET_SIZE(bases) == 0)
88 meta = (PyObject *) (&PyType_Type);
89 else {
90 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
91 meta = (PyObject *) (base0->ob_type);
92 }
93 Py_INCREF(meta);
94 }
95 prep = PyObject_GetAttrString(meta, "__prepare__");
96 if (prep == NULL) {
97 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
98 PyErr_Clear();
99 ns = PyDict_New();
100 }
101 else {
102 Py_DECREF(meta);
103 Py_XDECREF(mkw);
104 Py_DECREF(bases);
105 return NULL;
106 }
107 }
108 else {
109 PyObject *pargs = PyTuple_Pack(2, name, bases);
110 if (pargs == NULL) {
111 Py_DECREF(prep);
112 Py_DECREF(meta);
113 Py_XDECREF(mkw);
114 Py_DECREF(bases);
115 return NULL;
116 }
117 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
118 Py_DECREF(pargs);
119 Py_DECREF(prep);
120 }
121 if (ns == NULL) {
122 Py_DECREF(meta);
123 Py_XDECREF(mkw);
124 Py_DECREF(bases);
125 return NULL;
126 }
127 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
128 if (cell != NULL) {
129 PyObject *margs;
130 margs = PyTuple_Pack(3, name, bases, ns);
131 if (margs != NULL) {
132 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
133 Py_DECREF(margs);
134 }
135 if (cls != NULL && PyCell_Check(cell)) {
136 Py_INCREF(cls);
137 PyCell_SET(cell, cls);
138 }
139 Py_DECREF(cell);
140 }
141 Py_DECREF(ns);
142 Py_DECREF(meta);
143 Py_XDECREF(mkw);
144 Py_DECREF(bases);
145 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000146}
147
148PyDoc_STRVAR(build_class_doc,
149"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
150\n\
151Internal helper function used by the class statement.");
152
153static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000154builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
157 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400158 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000160
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400161 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 kwlist, &name, &globals, &locals, &fromlist, &level))
163 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400164 return PyImport_ImportModuleLevelObject(name, globals, locals,
165 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000166}
167
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000168PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000169"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000170\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000171Import a module. Because this function is meant for use by the Python\n\
172interpreter and not for general use it is better to use\n\
173importlib.import_module() to programmatically import a module.\n\
174\n\
175The globals argument is only used to determine the context;\n\
176they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000177should be a list of names to emulate ``from name import ...'', or an\n\
178empty list to emulate ``import name''.\n\
179When importing a module from a package, note that __import__('A.B', ...)\n\
180returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000181fromlist is not empty. Level is used to determine whether to perform \n\
182absolute or relative imports. -1 is the original strategy of attempting\n\
183both absolute and relative imports, 0 is absolute, a positive number\n\
184is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000185
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000186
Guido van Rossum79f25d91997-04-29 20:08:16 +0000187static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000188builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000191}
192
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000193PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000194"abs(number) -> number\n\
195\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000196Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000197
Raymond Hettinger96229b12005-03-11 06:49:40 +0000198static PyObject *
199builtin_all(PyObject *self, PyObject *v)
200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 PyObject *it, *item;
202 PyObject *(*iternext)(PyObject *);
203 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 it = PyObject_GetIter(v);
206 if (it == NULL)
207 return NULL;
208 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 for (;;) {
211 item = iternext(it);
212 if (item == NULL)
213 break;
214 cmp = PyObject_IsTrue(item);
215 Py_DECREF(item);
216 if (cmp < 0) {
217 Py_DECREF(it);
218 return NULL;
219 }
220 if (cmp == 0) {
221 Py_DECREF(it);
222 Py_RETURN_FALSE;
223 }
224 }
225 Py_DECREF(it);
226 if (PyErr_Occurred()) {
227 if (PyErr_ExceptionMatches(PyExc_StopIteration))
228 PyErr_Clear();
229 else
230 return NULL;
231 }
232 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000233}
234
235PyDoc_STRVAR(all_doc,
236"all(iterable) -> bool\n\
237\n\
238Return True if bool(x) is True for all values x in the iterable.");
239
240static PyObject *
241builtin_any(PyObject *self, PyObject *v)
242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 PyObject *it, *item;
244 PyObject *(*iternext)(PyObject *);
245 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 it = PyObject_GetIter(v);
248 if (it == NULL)
249 return NULL;
250 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 for (;;) {
253 item = iternext(it);
254 if (item == NULL)
255 break;
256 cmp = PyObject_IsTrue(item);
257 Py_DECREF(item);
258 if (cmp < 0) {
259 Py_DECREF(it);
260 return NULL;
261 }
262 if (cmp == 1) {
263 Py_DECREF(it);
264 Py_RETURN_TRUE;
265 }
266 }
267 Py_DECREF(it);
268 if (PyErr_Occurred()) {
269 if (PyErr_ExceptionMatches(PyExc_StopIteration))
270 PyErr_Clear();
271 else
272 return NULL;
273 }
274 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000275}
276
277PyDoc_STRVAR(any_doc,
278"any(iterable) -> bool\n\
279\n\
280Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000281
Georg Brandl559e5d72008-06-11 18:37:52 +0000282static PyObject *
283builtin_ascii(PyObject *self, PyObject *v)
284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000286}
287
288PyDoc_STRVAR(ascii_doc,
289"ascii(object) -> string\n\
290\n\
291As repr(), return a string containing a printable representation of an\n\
292object, but escape the non-ASCII characters in the string returned by\n\
293repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
294to that returned by repr() in Python 2.");
295
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000296
Guido van Rossum79f25d91997-04-29 20:08:16 +0000297static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000298builtin_bin(PyObject *self, PyObject *v)
299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000301}
302
303PyDoc_STRVAR(bin_doc,
304"bin(number) -> string\n\
305\n\
306Return the binary representation of an integer or long integer.");
307
308
Antoine Pitroue71362d2010-11-27 22:00:11 +0000309static PyObject *
310builtin_callable(PyObject *self, PyObject *v)
311{
312 return PyBool_FromLong((long)PyCallable_Check(v));
313}
314
315PyDoc_STRVAR(callable_doc,
316"callable(object) -> bool\n\
317\n\
318Return whether the object is callable (i.e., some kind of function).\n\
319Note that classes are callable, as are instances of classes with a\n\
320__call__() method.");
321
322
Raymond Hettinger17301e92008-03-13 00:19:26 +0000323typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 PyObject_HEAD
325 PyObject *func;
326 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000327} filterobject;
328
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000329static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000330filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 PyObject *func, *seq;
333 PyObject *it;
334 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
337 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
340 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 /* Get iterator. */
343 it = PyObject_GetIter(seq);
344 if (it == NULL)
345 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 /* create filterobject structure */
348 lz = (filterobject *)type->tp_alloc(type, 0);
349 if (lz == NULL) {
350 Py_DECREF(it);
351 return NULL;
352 }
353 Py_INCREF(func);
354 lz->func = func;
355 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000358}
359
360static void
361filter_dealloc(filterobject *lz)
362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 PyObject_GC_UnTrack(lz);
364 Py_XDECREF(lz->func);
365 Py_XDECREF(lz->it);
366 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000367}
368
369static int
370filter_traverse(filterobject *lz, visitproc visit, void *arg)
371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 Py_VISIT(lz->it);
373 Py_VISIT(lz->func);
374 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000375}
376
377static PyObject *
378filter_next(filterobject *lz)
379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 PyObject *item;
381 PyObject *it = lz->it;
382 long ok;
383 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 iternext = *Py_TYPE(it)->tp_iternext;
386 for (;;) {
387 item = iternext(it);
388 if (item == NULL)
389 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
392 ok = PyObject_IsTrue(item);
393 } else {
394 PyObject *good;
395 good = PyObject_CallFunctionObjArgs(lz->func,
396 item, NULL);
397 if (good == NULL) {
398 Py_DECREF(item);
399 return NULL;
400 }
401 ok = PyObject_IsTrue(good);
402 Py_DECREF(good);
403 }
404 if (ok)
405 return item;
406 Py_DECREF(item);
407 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000408}
409
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000410PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000411"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000412\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000413Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000414is true. If function is None, return the items that are true.");
415
416PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 PyVarObject_HEAD_INIT(&PyType_Type, 0)
418 "filter", /* tp_name */
419 sizeof(filterobject), /* tp_basicsize */
420 0, /* tp_itemsize */
421 /* methods */
422 (destructor)filter_dealloc, /* tp_dealloc */
423 0, /* tp_print */
424 0, /* tp_getattr */
425 0, /* tp_setattr */
426 0, /* tp_reserved */
427 0, /* tp_repr */
428 0, /* tp_as_number */
429 0, /* tp_as_sequence */
430 0, /* tp_as_mapping */
431 0, /* tp_hash */
432 0, /* tp_call */
433 0, /* tp_str */
434 PyObject_GenericGetAttr, /* tp_getattro */
435 0, /* tp_setattro */
436 0, /* tp_as_buffer */
437 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
438 Py_TPFLAGS_BASETYPE, /* tp_flags */
439 filter_doc, /* tp_doc */
440 (traverseproc)filter_traverse, /* tp_traverse */
441 0, /* tp_clear */
442 0, /* tp_richcompare */
443 0, /* tp_weaklistoffset */
444 PyObject_SelfIter, /* tp_iter */
445 (iternextfunc)filter_next, /* tp_iternext */
446 0, /* tp_methods */
447 0, /* tp_members */
448 0, /* tp_getset */
449 0, /* tp_base */
450 0, /* tp_dict */
451 0, /* tp_descr_get */
452 0, /* tp_descr_set */
453 0, /* tp_dictoffset */
454 0, /* tp_init */
455 PyType_GenericAlloc, /* tp_alloc */
456 filter_new, /* tp_new */
457 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000458};
459
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000460
Eric Smith8c663262007-08-25 02:26:07 +0000461static PyObject *
462builtin_format(PyObject *self, PyObject *args)
463{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000464 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000465 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000466
Eric Smith8fd3eba2008-02-17 19:48:00 +0000467 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000469
Eric Smith8fd3eba2008-02-17 19:48:00 +0000470 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000471}
472
Eric Smith8c663262007-08-25 02:26:07 +0000473PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000474"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000475\n\
Eric Smith81936692007-08-31 01:14:01 +0000476Returns value.__format__(format_spec)\n\
477format_spec defaults to \"\"");
478
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000479static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000480builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 if (!PyArg_ParseTuple(args, "i:chr", &x))
485 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000488}
489
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000490PyDoc_VAR(chr_doc) = PyDoc_STR(
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000491"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000492\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000493Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000494)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000495#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000496PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000497"\nIf 0x10000 <= i, a surrogate pair is returned."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000498)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000499#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000500;
Guido van Rossum09095f32000-03-10 23:00:52 +0000501
502
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000503static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000504source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 char *str;
507 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 if (PyUnicode_Check(cmd)) {
510 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Victor Stinnerf3fd7332011-03-02 01:03:11 +0000511 cmd = _PyUnicode_AsDefaultEncodedString(cmd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 if (cmd == NULL)
513 return NULL;
514 }
515 else if (!PyObject_CheckReadBuffer(cmd)) {
516 PyErr_Format(PyExc_TypeError,
517 "%s() arg 1 must be a %s object",
518 funcname, what);
519 return NULL;
520 }
521 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
522 return NULL;
523 }
524 if (strlen(str) != size) {
525 PyErr_SetString(PyExc_TypeError,
526 "source code string cannot contain null bytes");
527 return NULL;
528 }
529 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000530}
531
Guido van Rossum79f25d91997-04-29 20:08:16 +0000532static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000533builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 char *str;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000536 PyObject *filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 char *filename;
538 char *startstr;
539 int mode = -1;
540 int dont_inherit = 0;
541 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000542 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 int is_ast;
544 PyCompilerFlags cf;
545 PyObject *cmd;
546 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000547 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000549 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000550
Georg Brandl8334fd92010-12-04 10:26:46 +0000551 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000552 &cmd,
553 PyUnicode_FSConverter, &filename_obj,
554 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000555 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000557
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000558 filename = PyBytes_AS_STRING(filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 if (supplied_flags &
562 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
563 {
564 PyErr_SetString(PyExc_ValueError,
565 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000566 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 }
568 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000569
Georg Brandl8334fd92010-12-04 10:26:46 +0000570 if (optimize < -1 || optimize > 2) {
571 PyErr_SetString(PyExc_ValueError,
572 "compile(): invalid optimize value");
573 goto error;
574 }
575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 if (!dont_inherit) {
577 PyEval_MergeCompilerFlags(&cf);
578 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 if (strcmp(startstr, "exec") == 0)
581 mode = 0;
582 else if (strcmp(startstr, "eval") == 0)
583 mode = 1;
584 else if (strcmp(startstr, "single") == 0)
585 mode = 2;
586 else {
587 PyErr_SetString(PyExc_ValueError,
588 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000589 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 is_ast = PyAST_Check(cmd);
593 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000594 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 if (supplied_flags & PyCF_ONLY_AST) {
597 Py_INCREF(cmd);
598 result = cmd;
599 }
600 else {
601 PyArena *arena;
602 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 arena = PyArena_New();
605 mod = PyAST_obj2mod(cmd, arena, mode);
606 if (mod == NULL) {
607 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000608 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 }
Georg Brandl8334fd92010-12-04 10:26:46 +0000610 result = (PyObject*)PyAST_CompileEx(mod, filename,
611 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 PyArena_Free(arena);
613 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000614 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
618 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000619 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000620
Georg Brandl8334fd92010-12-04 10:26:46 +0000621 result = Py_CompileStringExFlags(str, filename, start[mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000622 goto finally;
623
624error:
625 result = NULL;
626finally:
627 Py_DECREF(filename_obj);
628 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000629}
630
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000631PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000632"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000633\n\
634Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000635into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000636The filename will be used for run-time error messages.\n\
637The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000638single (interactive) statement, or 'eval' to compile an expression.\n\
639The flags argument, if present, controls which future statements influence\n\
640the compilation of the code.\n\
641The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
642the effects of any future statements in effect in the code calling\n\
643compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000644in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000645
Guido van Rossum79f25d91997-04-29 20:08:16 +0000646static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000647builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
652 return NULL;
653 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000654}
655
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000656PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000657"dir([object]) -> list of strings\n"
658"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000659"If called without an argument, return the names in the current scope.\n"
660"Else, return an alphabetized list of names comprising (some of) the attributes\n"
661"of the given object, and of attributes reachable from it.\n"
662"If the object supplies a method named __dir__, it will be used; otherwise\n"
663"the default dir() logic is used and returns:\n"
664" for a module object: the module's attributes.\n"
665" for a class object: its attributes, and recursively the attributes\n"
666" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000667" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000668" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000669
Guido van Rossum79f25d91997-04-29 20:08:16 +0000670static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000671builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
676 return NULL;
677 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000678}
679
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000680PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000681"divmod(x, y) -> (div, mod)\n\
682\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000683Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000684
685
Guido van Rossum79f25d91997-04-29 20:08:16 +0000686static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000687builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 PyObject *cmd, *result, *tmp = NULL;
690 PyObject *globals = Py_None, *locals = Py_None;
691 char *str;
692 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
695 return NULL;
696 if (locals != Py_None && !PyMapping_Check(locals)) {
697 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
698 return NULL;
699 }
700 if (globals != Py_None && !PyDict_Check(globals)) {
701 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
702 "globals must be a real dict; try eval(expr, {}, mapping)"
703 : "globals must be a dict");
704 return NULL;
705 }
706 if (globals == Py_None) {
707 globals = PyEval_GetGlobals();
708 if (locals == Py_None)
709 locals = PyEval_GetLocals();
710 }
711 else if (locals == Py_None)
712 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 if (globals == NULL || locals == NULL) {
715 PyErr_SetString(PyExc_TypeError,
716 "eval must be given globals and locals "
717 "when called without a frame");
718 return NULL;
719 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
722 if (PyDict_SetItemString(globals, "__builtins__",
723 PyEval_GetBuiltins()) != 0)
724 return NULL;
725 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 if (PyCode_Check(cmd)) {
728 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
729 PyErr_SetString(PyExc_TypeError,
730 "code object passed to eval() may not contain free variables");
731 return NULL;
732 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000733 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
737 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
738 if (str == NULL)
739 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 while (*str == ' ' || *str == '\t')
742 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 (void)PyEval_MergeCompilerFlags(&cf);
745 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
746 Py_XDECREF(tmp);
747 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000748}
749
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000750PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000751"eval(source[, globals[, locals]]) -> value\n\
752\n\
753Evaluate the source in the context of globals and locals.\n\
754The source may be a string representing a Python expression\n\
755or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000756The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000757defaulting to the current globals and locals.\n\
758If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000759
Georg Brandl7cae87c2006-09-06 06:51:57 +0000760static PyObject *
761builtin_exec(PyObject *self, PyObject *args)
762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 PyObject *v;
764 PyObject *prog, *globals = Py_None, *locals = Py_None;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
767 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (globals == Py_None) {
770 globals = PyEval_GetGlobals();
771 if (locals == Py_None) {
772 locals = PyEval_GetLocals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 }
774 if (!globals || !locals) {
775 PyErr_SetString(PyExc_SystemError,
776 "globals and locals cannot be NULL");
777 return NULL;
778 }
779 }
780 else if (locals == Py_None)
781 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 if (!PyDict_Check(globals)) {
784 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
785 globals->ob_type->tp_name);
786 return NULL;
787 }
788 if (!PyMapping_Check(locals)) {
789 PyErr_Format(PyExc_TypeError,
790 "arg 3 must be a mapping or None, not %.100s",
791 locals->ob_type->tp_name);
792 return NULL;
793 }
794 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
795 if (PyDict_SetItemString(globals, "__builtins__",
796 PyEval_GetBuiltins()) != 0)
797 return NULL;
798 }
799
800 if (PyCode_Check(prog)) {
801 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
802 PyErr_SetString(PyExc_TypeError,
803 "code object passed to exec() may not "
804 "contain free variables");
805 return NULL;
806 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000807 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 }
809 else {
810 char *str;
811 PyCompilerFlags cf;
812 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
813 str = source_as_string(prog, "exec",
814 "string, bytes or code", &cf);
815 if (str == NULL)
816 return NULL;
817 if (PyEval_MergeCompilerFlags(&cf))
818 v = PyRun_StringFlags(str, Py_file_input, globals,
819 locals, &cf);
820 else
821 v = PyRun_String(str, Py_file_input, globals, locals);
822 }
823 if (v == NULL)
824 return NULL;
825 Py_DECREF(v);
826 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000827}
828
829PyDoc_STRVAR(exec_doc,
830"exec(object[, globals[, locals]])\n\
831\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000832Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000833object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000834The globals and locals are dictionaries, defaulting to the current\n\
835globals and locals. If only globals is given, locals defaults to it.");
836
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000837
Guido van Rossum79f25d91997-04-29 20:08:16 +0000838static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000839builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 PyObject *v, *result, *dflt = NULL;
842 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
845 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 if (!PyUnicode_Check(name)) {
848 PyErr_SetString(PyExc_TypeError,
849 "getattr(): attribute name must be string");
850 return NULL;
851 }
852 result = PyObject_GetAttr(v, name);
853 if (result == NULL && dflt != NULL &&
854 PyErr_ExceptionMatches(PyExc_AttributeError))
855 {
856 PyErr_Clear();
857 Py_INCREF(dflt);
858 result = dflt;
859 }
860 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000861}
862
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000863PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000864"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000865\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000866Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
867When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000868exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000869
870
Guido van Rossum79f25d91997-04-29 20:08:16 +0000871static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000872builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 d = PyEval_GetGlobals();
877 Py_XINCREF(d);
878 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000879}
880
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000881PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000882"globals() -> dictionary\n\
883\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000884Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000885
886
Guido van Rossum79f25d91997-04-29 20:08:16 +0000887static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000888builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 PyObject *v;
891 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
894 return NULL;
895 if (!PyUnicode_Check(name)) {
896 PyErr_SetString(PyExc_TypeError,
897 "hasattr(): attribute name must be string");
898 return NULL;
899 }
900 v = PyObject_GetAttr(v, name);
901 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000902 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000904 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000906 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 }
908 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000909 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000910}
911
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000912PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000913"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000914\n\
915Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000916(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000917
918
Guido van Rossum79f25d91997-04-29 20:08:16 +0000919static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000920builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000923}
924
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000925PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000926"id(object) -> integer\n\
927\n\
928Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000929simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000930
931
Raymond Hettingera6c60372008-03-13 01:26:19 +0000932/* map object ************************************************************/
933
934typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 PyObject_HEAD
936 PyObject *iters;
937 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000938} mapobject;
939
Guido van Rossum79f25d91997-04-29 20:08:16 +0000940static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000941map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 PyObject *it, *iters, *func;
944 mapobject *lz;
945 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
948 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 numargs = PyTuple_Size(args);
951 if (numargs < 2) {
952 PyErr_SetString(PyExc_TypeError,
953 "map() must have at least two arguments.");
954 return NULL;
955 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 iters = PyTuple_New(numargs-1);
958 if (iters == NULL)
959 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 for (i=1 ; i<numargs ; i++) {
962 /* Get iterator. */
963 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
964 if (it == NULL) {
965 Py_DECREF(iters);
966 return NULL;
967 }
968 PyTuple_SET_ITEM(iters, i-1, it);
969 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 /* create mapobject structure */
972 lz = (mapobject *)type->tp_alloc(type, 0);
973 if (lz == NULL) {
974 Py_DECREF(iters);
975 return NULL;
976 }
977 lz->iters = iters;
978 func = PyTuple_GET_ITEM(args, 0);
979 Py_INCREF(func);
980 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000983}
984
985static void
986map_dealloc(mapobject *lz)
987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 PyObject_GC_UnTrack(lz);
989 Py_XDECREF(lz->iters);
990 Py_XDECREF(lz->func);
991 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +0000992}
993
994static int
995map_traverse(mapobject *lz, visitproc visit, void *arg)
996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 Py_VISIT(lz->iters);
998 Py_VISIT(lz->func);
999 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001000}
1001
1002static PyObject *
1003map_next(mapobject *lz)
1004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 PyObject *val;
1006 PyObject *argtuple;
1007 PyObject *result;
1008 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 numargs = PyTuple_Size(lz->iters);
1011 argtuple = PyTuple_New(numargs);
1012 if (argtuple == NULL)
1013 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 for (i=0 ; i<numargs ; i++) {
1016 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1017 if (val == NULL) {
1018 Py_DECREF(argtuple);
1019 return NULL;
1020 }
1021 PyTuple_SET_ITEM(argtuple, i, val);
1022 }
1023 result = PyObject_Call(lz->func, argtuple, NULL);
1024 Py_DECREF(argtuple);
1025 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001026}
1027
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001028PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001029"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001030\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001031Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001033
Raymond Hettingera6c60372008-03-13 01:26:19 +00001034PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1036 "map", /* tp_name */
1037 sizeof(mapobject), /* tp_basicsize */
1038 0, /* tp_itemsize */
1039 /* methods */
1040 (destructor)map_dealloc, /* tp_dealloc */
1041 0, /* tp_print */
1042 0, /* tp_getattr */
1043 0, /* tp_setattr */
1044 0, /* tp_reserved */
1045 0, /* tp_repr */
1046 0, /* tp_as_number */
1047 0, /* tp_as_sequence */
1048 0, /* tp_as_mapping */
1049 0, /* tp_hash */
1050 0, /* tp_call */
1051 0, /* tp_str */
1052 PyObject_GenericGetAttr, /* tp_getattro */
1053 0, /* tp_setattro */
1054 0, /* tp_as_buffer */
1055 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1056 Py_TPFLAGS_BASETYPE, /* tp_flags */
1057 map_doc, /* tp_doc */
1058 (traverseproc)map_traverse, /* tp_traverse */
1059 0, /* tp_clear */
1060 0, /* tp_richcompare */
1061 0, /* tp_weaklistoffset */
1062 PyObject_SelfIter, /* tp_iter */
1063 (iternextfunc)map_next, /* tp_iternext */
1064 0, /* tp_methods */
1065 0, /* tp_members */
1066 0, /* tp_getset */
1067 0, /* tp_base */
1068 0, /* tp_dict */
1069 0, /* tp_descr_get */
1070 0, /* tp_descr_set */
1071 0, /* tp_dictoffset */
1072 0, /* tp_init */
1073 PyType_GenericAlloc, /* tp_alloc */
1074 map_new, /* tp_new */
1075 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001076};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001077
Guido van Rossum79f25d91997-04-29 20:08:16 +00001078static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001079builtin_next(PyObject *self, PyObject *args)
1080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 PyObject *it, *res;
1082 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1085 return NULL;
1086 if (!PyIter_Check(it)) {
1087 PyErr_Format(PyExc_TypeError,
1088 "%.200s object is not an iterator",
1089 it->ob_type->tp_name);
1090 return NULL;
1091 }
1092
1093 res = (*it->ob_type->tp_iternext)(it);
1094 if (res != NULL) {
1095 return res;
1096 } else if (def != NULL) {
1097 if (PyErr_Occurred()) {
1098 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1099 return NULL;
1100 PyErr_Clear();
1101 }
1102 Py_INCREF(def);
1103 return def;
1104 } else if (PyErr_Occurred()) {
1105 return NULL;
1106 } else {
1107 PyErr_SetNone(PyExc_StopIteration);
1108 return NULL;
1109 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001110}
1111
1112PyDoc_STRVAR(next_doc,
1113"next(iterator[, default])\n\
1114\n\
1115Return the next item from the iterator. If default is given and the iterator\n\
1116is exhausted, it is returned instead of raising StopIteration.");
1117
1118
1119static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001120builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 PyObject *v;
1123 PyObject *name;
1124 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1127 return NULL;
1128 if (PyObject_SetAttr(v, name, value) != 0)
1129 return NULL;
1130 Py_INCREF(Py_None);
1131 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001132}
1133
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001134PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001135"setattr(object, name, value)\n\
1136\n\
1137Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001138``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001139
1140
Guido van Rossum79f25d91997-04-29 20:08:16 +00001141static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001142builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 PyObject *v;
1145 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1148 return NULL;
1149 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1150 return NULL;
1151 Py_INCREF(Py_None);
1152 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001153}
1154
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001155PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001156"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001157\n\
1158Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001159``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001160
1161
Guido van Rossum79f25d91997-04-29 20:08:16 +00001162static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001163builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001164{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001165 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 x = PyObject_Hash(v);
1168 if (x == -1)
1169 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001170 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001171}
1172
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001173PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001174"hash(object) -> integer\n\
1175\n\
1176Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001177the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001178
1179
Guido van Rossum79f25d91997-04-29 20:08:16 +00001180static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001181builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001184}
1185
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001186PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001187"hex(number) -> string\n\
1188\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001189Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001190
1191
Guido van Rossum79f25d91997-04-29 20:08:16 +00001192static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001193builtin_iter(PyObject *self, PyObject *args)
1194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1198 return NULL;
1199 if (w == NULL)
1200 return PyObject_GetIter(v);
1201 if (!PyCallable_Check(v)) {
1202 PyErr_SetString(PyExc_TypeError,
1203 "iter(v, w): v must be callable");
1204 return NULL;
1205 }
1206 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001207}
1208
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001209PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001210"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001211iter(callable, sentinel) -> iterator\n\
1212\n\
1213Get an iterator from an object. In the first form, the argument must\n\
1214supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001215In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001216
1217
1218static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001219builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 res = PyObject_Size(v);
1224 if (res < 0 && PyErr_Occurred())
1225 return NULL;
1226 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001227}
1228
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001229PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001230"len(object) -> integer\n\
1231\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001232Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001233
1234
Guido van Rossum79f25d91997-04-29 20:08:16 +00001235static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001236builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 d = PyEval_GetLocals();
1241 Py_XINCREF(d);
1242 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001243}
1244
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001245PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001246"locals() -> dictionary\n\
1247\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001248Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001249
1250
Guido van Rossum79f25d91997-04-29 20:08:16 +00001251static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001252min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1255 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 if (PyTuple_Size(args) > 1)
1258 v = args;
1259 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1260 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1263 keyfunc = PyDict_GetItemString(kwds, "key");
1264 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1265 PyErr_Format(PyExc_TypeError,
1266 "%s() got an unexpected keyword argument", name);
1267 return NULL;
1268 }
1269 Py_INCREF(keyfunc);
1270 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 it = PyObject_GetIter(v);
1273 if (it == NULL) {
1274 Py_XDECREF(keyfunc);
1275 return NULL;
1276 }
Tim Petersc3074532001-05-03 07:00:32 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 maxitem = NULL; /* the result */
1279 maxval = NULL; /* the value associated with the result */
1280 while (( item = PyIter_Next(it) )) {
1281 /* get the value from the key function */
1282 if (keyfunc != NULL) {
1283 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1284 if (val == NULL)
1285 goto Fail_it_item;
1286 }
1287 /* no key function; the value is the item */
1288 else {
1289 val = item;
1290 Py_INCREF(val);
1291 }
Tim Petersc3074532001-05-03 07:00:32 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 /* maximum value and item are unset; set them */
1294 if (maxval == NULL) {
1295 maxitem = item;
1296 maxval = val;
1297 }
1298 /* maximum value and item are set; update them as necessary */
1299 else {
1300 int cmp = PyObject_RichCompareBool(val, maxval, op);
1301 if (cmp < 0)
1302 goto Fail_it_item_and_val;
1303 else if (cmp > 0) {
1304 Py_DECREF(maxval);
1305 Py_DECREF(maxitem);
1306 maxval = val;
1307 maxitem = item;
1308 }
1309 else {
1310 Py_DECREF(item);
1311 Py_DECREF(val);
1312 }
1313 }
1314 }
1315 if (PyErr_Occurred())
1316 goto Fail_it;
1317 if (maxval == NULL) {
1318 PyErr_Format(PyExc_ValueError,
1319 "%s() arg is an empty sequence", name);
1320 assert(maxitem == NULL);
1321 }
1322 else
1323 Py_DECREF(maxval);
1324 Py_DECREF(it);
1325 Py_XDECREF(keyfunc);
1326 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001327
1328Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001330Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001332Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 Py_XDECREF(maxval);
1334 Py_XDECREF(maxitem);
1335 Py_DECREF(it);
1336 Py_XDECREF(keyfunc);
1337 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001338}
1339
Guido van Rossum79f25d91997-04-29 20:08:16 +00001340static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001341builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001344}
1345
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001346PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001347"min(iterable[, key=func]) -> value\n\
1348min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001349\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001350With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001351With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001352
1353
Guido van Rossum79f25d91997-04-29 20:08:16 +00001354static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001355builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001358}
1359
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001360PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001361"max(iterable[, key=func]) -> value\n\
1362max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001363\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001364With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001365With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001366
1367
Guido van Rossum79f25d91997-04-29 20:08:16 +00001368static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001369builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001372}
1373
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001374PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001375"oct(number) -> string\n\
1376\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001377Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001378
1379
Guido van Rossum79f25d91997-04-29 20:08:16 +00001380static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001381builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 long ord;
1384 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 if (PyBytes_Check(obj)) {
1387 size = PyBytes_GET_SIZE(obj);
1388 if (size == 1) {
1389 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1390 return PyLong_FromLong(ord);
1391 }
1392 }
1393 else if (PyUnicode_Check(obj)) {
1394 size = PyUnicode_GET_SIZE(obj);
1395 if (size == 1) {
1396 ord = (long)*PyUnicode_AS_UNICODE(obj);
1397 return PyLong_FromLong(ord);
1398 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001399#ifndef Py_UNICODE_WIDE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 if (size == 2) {
1401 /* Decode a valid surrogate pair */
1402 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1403 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1404 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1405 0xDC00 <= c1 && c1 <= 0xDFFF) {
1406 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1407 0x00010000);
1408 return PyLong_FromLong(ord);
1409 }
1410 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001411#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 }
1413 else if (PyByteArray_Check(obj)) {
1414 /* XXX Hopefully this is temporary */
1415 size = PyByteArray_GET_SIZE(obj);
1416 if (size == 1) {
1417 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1418 return PyLong_FromLong(ord);
1419 }
1420 }
1421 else {
1422 PyErr_Format(PyExc_TypeError,
1423 "ord() expected string of length 1, but " \
1424 "%.200s found", obj->ob_type->tp_name);
1425 return NULL;
1426 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 PyErr_Format(PyExc_TypeError,
1429 "ord() expected a character, "
1430 "but string of length %zd found",
1431 size);
1432 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001433}
1434
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001435PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001436"ord(c) -> integer\n\
1437\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001438Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001439)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001440#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001441PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001442"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001443)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001444#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001445;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001446
1447
Guido van Rossum79f25d91997-04-29 20:08:16 +00001448static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001449builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1454 return NULL;
1455 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001456}
1457
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001458PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001459"pow(x, y[, z]) -> number\n\
1460\n\
1461With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001462equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001463
1464
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001465
Guido van Rossum34343512006-11-30 22:13:52 +00001466static PyObject *
1467builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 static char *kwlist[] = {"sep", "end", "file", 0};
1470 static PyObject *dummy_args;
1471 PyObject *sep = NULL, *end = NULL, *file = NULL;
1472 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 if (dummy_args == NULL) {
1475 if (!(dummy_args = PyTuple_New(0)))
1476 return NULL;
1477 }
1478 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1479 kwlist, &sep, &end, &file))
1480 return NULL;
1481 if (file == NULL || file == Py_None) {
1482 file = PySys_GetObject("stdout");
1483 /* sys.stdout may be None when FILE* stdout isn't connected */
1484 if (file == Py_None)
1485 Py_RETURN_NONE;
1486 }
Guido van Rossum34343512006-11-30 22:13:52 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 if (sep == Py_None) {
1489 sep = NULL;
1490 }
1491 else if (sep && !PyUnicode_Check(sep)) {
1492 PyErr_Format(PyExc_TypeError,
1493 "sep must be None or a string, not %.200s",
1494 sep->ob_type->tp_name);
1495 return NULL;
1496 }
1497 if (end == Py_None) {
1498 end = NULL;
1499 }
1500 else if (end && !PyUnicode_Check(end)) {
1501 PyErr_Format(PyExc_TypeError,
1502 "end must be None or a string, not %.200s",
1503 end->ob_type->tp_name);
1504 return NULL;
1505 }
Guido van Rossum34343512006-11-30 22:13:52 +00001506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 for (i = 0; i < PyTuple_Size(args); i++) {
1508 if (i > 0) {
1509 if (sep == NULL)
1510 err = PyFile_WriteString(" ", file);
1511 else
1512 err = PyFile_WriteObject(sep, file,
1513 Py_PRINT_RAW);
1514 if (err)
1515 return NULL;
1516 }
1517 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1518 Py_PRINT_RAW);
1519 if (err)
1520 return NULL;
1521 }
Guido van Rossum34343512006-11-30 22:13:52 +00001522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 if (end == NULL)
1524 err = PyFile_WriteString("\n", file);
1525 else
1526 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1527 if (err)
1528 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001531}
1532
1533PyDoc_STRVAR(print_doc,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001534"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001535\n\
1536Prints the values to a stream, or to sys.stdout by default.\n\
1537Optional keyword arguments:\n\
1538file: a file-like object (stream); defaults to the current sys.stdout.\n\
1539sep: string inserted between values, default a space.\n\
1540end: string appended after the last value, default a newline.");
1541
1542
Guido van Rossuma88a0332007-02-26 16:59:55 +00001543static PyObject *
1544builtin_input(PyObject *self, PyObject *args)
1545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 PyObject *promptarg = NULL;
1547 PyObject *fin = PySys_GetObject("stdin");
1548 PyObject *fout = PySys_GetObject("stdout");
1549 PyObject *ferr = PySys_GetObject("stderr");
1550 PyObject *tmp;
1551 long fd;
1552 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 /* Parse arguments */
1555 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1556 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 /* Check that stdin/out/err are intact */
1559 if (fin == NULL || fin == Py_None) {
1560 PyErr_SetString(PyExc_RuntimeError,
1561 "input(): lost sys.stdin");
1562 return NULL;
1563 }
1564 if (fout == NULL || fout == Py_None) {
1565 PyErr_SetString(PyExc_RuntimeError,
1566 "input(): lost sys.stdout");
1567 return NULL;
1568 }
1569 if (ferr == NULL || ferr == Py_None) {
1570 PyErr_SetString(PyExc_RuntimeError,
1571 "input(): lost sys.stderr");
1572 return NULL;
1573 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 /* First of all, flush stderr */
1576 tmp = PyObject_CallMethod(ferr, "flush", "");
1577 if (tmp == NULL)
1578 PyErr_Clear();
1579 else
1580 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 /* We should only use (GNU) readline if Python's sys.stdin and
1583 sys.stdout are the same as C's stdin and stdout, because we
1584 need to pass it those. */
1585 tmp = PyObject_CallMethod(fin, "fileno", "");
1586 if (tmp == NULL) {
1587 PyErr_Clear();
1588 tty = 0;
1589 }
1590 else {
1591 fd = PyLong_AsLong(tmp);
1592 Py_DECREF(tmp);
1593 if (fd < 0 && PyErr_Occurred())
1594 return NULL;
1595 tty = fd == fileno(stdin) && isatty(fd);
1596 }
1597 if (tty) {
1598 tmp = PyObject_CallMethod(fout, "fileno", "");
1599 if (tmp == NULL)
1600 PyErr_Clear();
1601 else {
1602 fd = PyLong_AsLong(tmp);
1603 Py_DECREF(tmp);
1604 if (fd < 0 && PyErr_Occurred())
1605 return NULL;
1606 tty = fd == fileno(stdout) && isatty(fd);
1607 }
1608 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 /* If we're interactive, use (GNU) readline */
1611 if (tty) {
1612 PyObject *po;
1613 char *prompt;
1614 char *s;
1615 PyObject *stdin_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001616 char *stdin_encoding_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001618 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1621 if (!stdin_encoding)
1622 /* stdin is a text stream, so it must have an
1623 encoding. */
1624 return NULL;
Victor Stinner306f0102010-05-19 01:06:22 +00001625 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
1626 if (stdin_encoding_str == NULL) {
1627 Py_DECREF(stdin_encoding);
1628 return NULL;
1629 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 tmp = PyObject_CallMethod(fout, "flush", "");
1631 if (tmp == NULL)
1632 PyErr_Clear();
1633 else
1634 Py_DECREF(tmp);
1635 if (promptarg != NULL) {
1636 PyObject *stringpo;
1637 PyObject *stdout_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001638 char *stdout_encoding_str;
1639 stdout_encoding = PyObject_GetAttrString(fout, "encoding");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 if (stdout_encoding == NULL) {
1641 Py_DECREF(stdin_encoding);
1642 return NULL;
1643 }
Victor Stinner306f0102010-05-19 01:06:22 +00001644 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
1645 if (stdout_encoding_str == NULL) {
1646 Py_DECREF(stdin_encoding);
1647 Py_DECREF(stdout_encoding);
1648 return NULL;
1649 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 stringpo = PyObject_Str(promptarg);
1651 if (stringpo == NULL) {
1652 Py_DECREF(stdin_encoding);
1653 Py_DECREF(stdout_encoding);
1654 return NULL;
1655 }
1656 po = PyUnicode_AsEncodedString(stringpo,
Victor Stinner306f0102010-05-19 01:06:22 +00001657 stdout_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 Py_DECREF(stdout_encoding);
1659 Py_DECREF(stringpo);
1660 if (po == NULL) {
1661 Py_DECREF(stdin_encoding);
1662 return NULL;
1663 }
1664 prompt = PyBytes_AsString(po);
1665 if (prompt == NULL) {
1666 Py_DECREF(stdin_encoding);
1667 Py_DECREF(po);
1668 return NULL;
1669 }
1670 }
1671 else {
1672 po = NULL;
1673 prompt = "";
1674 }
1675 s = PyOS_Readline(stdin, stdout, prompt);
1676 Py_XDECREF(po);
1677 if (s == NULL) {
1678 if (!PyErr_Occurred())
1679 PyErr_SetNone(PyExc_KeyboardInterrupt);
1680 Py_DECREF(stdin_encoding);
1681 return NULL;
1682 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001683
1684 len = strlen(s);
1685 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 PyErr_SetNone(PyExc_EOFError);
1687 result = NULL;
1688 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001689 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 if (len > PY_SSIZE_T_MAX) {
1691 PyErr_SetString(PyExc_OverflowError,
1692 "input: input too long");
1693 result = NULL;
1694 }
1695 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001696 len--; /* strip trailing '\n' */
1697 if (len != 0 && s[len-1] == '\r')
1698 len--; /* strip trailing '\r' */
1699 result = PyUnicode_Decode(s, len, stdin_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 }
1701 }
1702 Py_DECREF(stdin_encoding);
1703 PyMem_FREE(s);
1704 return result;
1705 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 /* Fallback if we're not interactive */
1708 if (promptarg != NULL) {
1709 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1710 return NULL;
1711 }
1712 tmp = PyObject_CallMethod(fout, "flush", "");
1713 if (tmp == NULL)
1714 PyErr_Clear();
1715 else
1716 Py_DECREF(tmp);
1717 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001718}
1719
1720PyDoc_STRVAR(input_doc,
1721"input([prompt]) -> string\n\
1722\n\
1723Read a string from standard input. The trailing newline is stripped.\n\
1724If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1725On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1726is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001727
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001728
Guido van Rossum79f25d91997-04-29 20:08:16 +00001729static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001730builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001733}
1734
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001735PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001736"repr(object) -> string\n\
1737\n\
1738Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001739For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001740
1741
Guido van Rossum79f25d91997-04-29 20:08:16 +00001742static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001743builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 static PyObject *round_str = NULL;
1746 PyObject *ndigits = NULL;
1747 static char *kwlist[] = {"number", "ndigits", 0};
1748 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1751 kwlist, &number, &ndigits))
1752 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 if (Py_TYPE(number)->tp_dict == NULL) {
1755 if (PyType_Ready(Py_TYPE(number)) < 0)
1756 return NULL;
1757 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 if (round_str == NULL) {
1760 round_str = PyUnicode_InternFromString("__round__");
1761 if (round_str == NULL)
1762 return NULL;
1763 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 round = _PyType_Lookup(Py_TYPE(number), round_str);
1766 if (round == NULL) {
1767 PyErr_Format(PyExc_TypeError,
1768 "type %.100s doesn't define __round__ method",
1769 Py_TYPE(number)->tp_name);
1770 return NULL;
1771 }
Alex Martelliae211f92007-08-22 23:21:33 +00001772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 if (ndigits == NULL)
1774 return PyObject_CallFunction(round, "O", number);
1775 else
1776 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001777}
1778
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001779PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001780"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001781\n\
1782Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001783This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001784same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001785
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001786
Raymond Hettinger64958a12003-12-17 20:43:33 +00001787static PyObject *
1788builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1791 PyObject *callable;
1792 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1793 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 /* args 1-3 should match listsort in Objects/listobject.c */
1796 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1797 kwlist, &seq, &keyfunc, &reverse))
1798 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 newlist = PySequence_List(seq);
1801 if (newlist == NULL)
1802 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 callable = PyObject_GetAttrString(newlist, "sort");
1805 if (callable == NULL) {
1806 Py_DECREF(newlist);
1807 return NULL;
1808 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 newargs = PyTuple_GetSlice(args, 1, 4);
1811 if (newargs == NULL) {
1812 Py_DECREF(newlist);
1813 Py_DECREF(callable);
1814 return NULL;
1815 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 v = PyObject_Call(callable, newargs, kwds);
1818 Py_DECREF(newargs);
1819 Py_DECREF(callable);
1820 if (v == NULL) {
1821 Py_DECREF(newlist);
1822 return NULL;
1823 }
1824 Py_DECREF(v);
1825 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001826}
1827
1828PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001829"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001830
Guido van Rossum79f25d91997-04-29 20:08:16 +00001831static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001832builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 PyObject *v = NULL;
1835 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1838 return NULL;
1839 if (v == NULL) {
1840 d = PyEval_GetLocals();
1841 if (d == NULL) {
1842 if (!PyErr_Occurred())
1843 PyErr_SetString(PyExc_SystemError,
1844 "vars(): no locals!?");
1845 }
1846 else
1847 Py_INCREF(d);
1848 }
1849 else {
1850 d = PyObject_GetAttrString(v, "__dict__");
1851 if (d == NULL) {
1852 PyErr_SetString(PyExc_TypeError,
1853 "vars() argument must have __dict__ attribute");
1854 return NULL;
1855 }
1856 }
1857 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001858}
1859
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001860PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001861"vars([object]) -> dictionary\n\
1862\n\
1863Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001864With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001865
Alex Martellia70b1912003-04-22 08:12:33 +00001866static PyObject*
1867builtin_sum(PyObject *self, PyObject *args)
1868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 PyObject *seq;
1870 PyObject *result = NULL;
1871 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1874 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 iter = PyObject_GetIter(seq);
1877 if (iter == NULL)
1878 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 if (result == NULL) {
1881 result = PyLong_FromLong(0);
1882 if (result == NULL) {
1883 Py_DECREF(iter);
1884 return NULL;
1885 }
1886 } else {
1887 /* reject string values for 'start' parameter */
1888 if (PyUnicode_Check(result)) {
1889 PyErr_SetString(PyExc_TypeError,
1890 "sum() can't sum strings [use ''.join(seq) instead]");
1891 Py_DECREF(iter);
1892 return NULL;
1893 }
1894 if (PyByteArray_Check(result)) {
1895 PyErr_SetString(PyExc_TypeError,
1896 "sum() can't sum bytes [use b''.join(seq) instead]");
1897 Py_DECREF(iter);
1898 return NULL;
1899 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 Py_INCREF(result);
1902 }
Alex Martellia70b1912003-04-22 08:12:33 +00001903
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001904#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1906 Assumes all inputs are the same type. If the assumption fails, default
1907 to the more general routine.
1908 */
1909 if (PyLong_CheckExact(result)) {
1910 int overflow;
1911 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1912 /* If this already overflowed, don't even enter the loop. */
1913 if (overflow == 0) {
1914 Py_DECREF(result);
1915 result = NULL;
1916 }
1917 while(result == NULL) {
1918 item = PyIter_Next(iter);
1919 if (item == NULL) {
1920 Py_DECREF(iter);
1921 if (PyErr_Occurred())
1922 return NULL;
1923 return PyLong_FromLong(i_result);
1924 }
1925 if (PyLong_CheckExact(item)) {
1926 long b = PyLong_AsLongAndOverflow(item, &overflow);
1927 long x = i_result + b;
1928 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1929 i_result = x;
1930 Py_DECREF(item);
1931 continue;
1932 }
1933 }
1934 /* Either overflowed or is not an int. Restore real objects and process normally */
1935 result = PyLong_FromLong(i_result);
1936 temp = PyNumber_Add(result, item);
1937 Py_DECREF(result);
1938 Py_DECREF(item);
1939 result = temp;
1940 if (result == NULL) {
1941 Py_DECREF(iter);
1942 return NULL;
1943 }
1944 }
1945 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 if (PyFloat_CheckExact(result)) {
1948 double f_result = PyFloat_AS_DOUBLE(result);
1949 Py_DECREF(result);
1950 result = NULL;
1951 while(result == NULL) {
1952 item = PyIter_Next(iter);
1953 if (item == NULL) {
1954 Py_DECREF(iter);
1955 if (PyErr_Occurred())
1956 return NULL;
1957 return PyFloat_FromDouble(f_result);
1958 }
1959 if (PyFloat_CheckExact(item)) {
1960 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1961 f_result += PyFloat_AS_DOUBLE(item);
1962 PyFPE_END_PROTECT(f_result)
1963 Py_DECREF(item);
1964 continue;
1965 }
1966 if (PyLong_CheckExact(item)) {
1967 long value;
1968 int overflow;
1969 value = PyLong_AsLongAndOverflow(item, &overflow);
1970 if (!overflow) {
1971 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1972 f_result += (double)value;
1973 PyFPE_END_PROTECT(f_result)
1974 Py_DECREF(item);
1975 continue;
1976 }
1977 }
1978 result = PyFloat_FromDouble(f_result);
1979 temp = PyNumber_Add(result, item);
1980 Py_DECREF(result);
1981 Py_DECREF(item);
1982 result = temp;
1983 if (result == NULL) {
1984 Py_DECREF(iter);
1985 return NULL;
1986 }
1987 }
1988 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001989#endif
1990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 for(;;) {
1992 item = PyIter_Next(iter);
1993 if (item == NULL) {
1994 /* error, or end-of-sequence */
1995 if (PyErr_Occurred()) {
1996 Py_DECREF(result);
1997 result = NULL;
1998 }
1999 break;
2000 }
2001 /* It's tempting to use PyNumber_InPlaceAdd instead of
2002 PyNumber_Add here, to avoid quadratic running time
2003 when doing 'sum(list_of_lists, [])'. However, this
2004 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 empty = []
2007 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 would change the value of empty. */
2010 temp = PyNumber_Add(result, item);
2011 Py_DECREF(result);
2012 Py_DECREF(item);
2013 result = temp;
2014 if (result == NULL)
2015 break;
2016 }
2017 Py_DECREF(iter);
2018 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002019}
2020
2021PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002022"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002023\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002024Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2025of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002026empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002027
2028
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002029static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002030builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 PyObject *inst;
2033 PyObject *cls;
2034 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2037 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 retval = PyObject_IsInstance(inst, cls);
2040 if (retval < 0)
2041 return NULL;
2042 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002043}
2044
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002045PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002046"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002047\n\
2048Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002049With a type as second argument, return whether that is the object's type.\n\
2050The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002051isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002052
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002053
2054static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002055builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 PyObject *derived;
2058 PyObject *cls;
2059 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2062 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 retval = PyObject_IsSubclass(derived, cls);
2065 if (retval < 0)
2066 return NULL;
2067 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002068}
2069
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002070PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002071"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002072\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002073Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2074When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2075is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002076
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002077
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002078typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 PyObject_HEAD
2080 Py_ssize_t tuplesize;
2081 PyObject *ittuple; /* tuple of iterators */
2082 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002083} zipobject;
2084
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002085static PyObject *
2086zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 zipobject *lz;
2089 Py_ssize_t i;
2090 PyObject *ittuple; /* tuple of iterators */
2091 PyObject *result;
2092 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2095 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 /* args must be a tuple */
2098 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 /* obtain iterators */
2101 ittuple = PyTuple_New(tuplesize);
2102 if (ittuple == NULL)
2103 return NULL;
2104 for (i=0; i < tuplesize; ++i) {
2105 PyObject *item = PyTuple_GET_ITEM(args, i);
2106 PyObject *it = PyObject_GetIter(item);
2107 if (it == NULL) {
2108 if (PyErr_ExceptionMatches(PyExc_TypeError))
2109 PyErr_Format(PyExc_TypeError,
2110 "zip argument #%zd must support iteration",
2111 i+1);
2112 Py_DECREF(ittuple);
2113 return NULL;
2114 }
2115 PyTuple_SET_ITEM(ittuple, i, it);
2116 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 /* create a result holder */
2119 result = PyTuple_New(tuplesize);
2120 if (result == NULL) {
2121 Py_DECREF(ittuple);
2122 return NULL;
2123 }
2124 for (i=0 ; i < tuplesize ; i++) {
2125 Py_INCREF(Py_None);
2126 PyTuple_SET_ITEM(result, i, Py_None);
2127 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 /* create zipobject structure */
2130 lz = (zipobject *)type->tp_alloc(type, 0);
2131 if (lz == NULL) {
2132 Py_DECREF(ittuple);
2133 Py_DECREF(result);
2134 return NULL;
2135 }
2136 lz->ittuple = ittuple;
2137 lz->tuplesize = tuplesize;
2138 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002141}
2142
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002143static void
2144zip_dealloc(zipobject *lz)
2145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 PyObject_GC_UnTrack(lz);
2147 Py_XDECREF(lz->ittuple);
2148 Py_XDECREF(lz->result);
2149 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002150}
2151
2152static int
2153zip_traverse(zipobject *lz, visitproc visit, void *arg)
2154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 Py_VISIT(lz->ittuple);
2156 Py_VISIT(lz->result);
2157 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002158}
2159
2160static PyObject *
2161zip_next(zipobject *lz)
2162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 Py_ssize_t i;
2164 Py_ssize_t tuplesize = lz->tuplesize;
2165 PyObject *result = lz->result;
2166 PyObject *it;
2167 PyObject *item;
2168 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 if (tuplesize == 0)
2171 return NULL;
2172 if (Py_REFCNT(result) == 1) {
2173 Py_INCREF(result);
2174 for (i=0 ; i < tuplesize ; i++) {
2175 it = PyTuple_GET_ITEM(lz->ittuple, i);
2176 item = (*Py_TYPE(it)->tp_iternext)(it);
2177 if (item == NULL) {
2178 Py_DECREF(result);
2179 return NULL;
2180 }
2181 olditem = PyTuple_GET_ITEM(result, i);
2182 PyTuple_SET_ITEM(result, i, item);
2183 Py_DECREF(olditem);
2184 }
2185 } else {
2186 result = PyTuple_New(tuplesize);
2187 if (result == NULL)
2188 return NULL;
2189 for (i=0 ; i < tuplesize ; i++) {
2190 it = PyTuple_GET_ITEM(lz->ittuple, i);
2191 item = (*Py_TYPE(it)->tp_iternext)(it);
2192 if (item == NULL) {
2193 Py_DECREF(result);
2194 return NULL;
2195 }
2196 PyTuple_SET_ITEM(result, i, item);
2197 }
2198 }
2199 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002200}
Barry Warsawbd599b52000-08-03 15:45:29 +00002201
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002202PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002203"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002204\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002205Return a zip object whose .__next__() method returns a tuple where\n\
2206the i-th element comes from the i-th iterable argument. The .__next__()\n\
2207method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002208is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002209
2210PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2212 "zip", /* tp_name */
2213 sizeof(zipobject), /* tp_basicsize */
2214 0, /* tp_itemsize */
2215 /* methods */
2216 (destructor)zip_dealloc, /* tp_dealloc */
2217 0, /* tp_print */
2218 0, /* tp_getattr */
2219 0, /* tp_setattr */
2220 0, /* tp_reserved */
2221 0, /* tp_repr */
2222 0, /* tp_as_number */
2223 0, /* tp_as_sequence */
2224 0, /* tp_as_mapping */
2225 0, /* tp_hash */
2226 0, /* tp_call */
2227 0, /* tp_str */
2228 PyObject_GenericGetAttr, /* tp_getattro */
2229 0, /* tp_setattro */
2230 0, /* tp_as_buffer */
2231 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2232 Py_TPFLAGS_BASETYPE, /* tp_flags */
2233 zip_doc, /* tp_doc */
2234 (traverseproc)zip_traverse, /* tp_traverse */
2235 0, /* tp_clear */
2236 0, /* tp_richcompare */
2237 0, /* tp_weaklistoffset */
2238 PyObject_SelfIter, /* tp_iter */
2239 (iternextfunc)zip_next, /* tp_iternext */
2240 0, /* tp_methods */
2241 0, /* tp_members */
2242 0, /* tp_getset */
2243 0, /* tp_base */
2244 0, /* tp_dict */
2245 0, /* tp_descr_get */
2246 0, /* tp_descr_set */
2247 0, /* tp_dictoffset */
2248 0, /* tp_init */
2249 PyType_GenericAlloc, /* tp_alloc */
2250 zip_new, /* tp_new */
2251 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002252};
Barry Warsawbd599b52000-08-03 15:45:29 +00002253
2254
Guido van Rossum79f25d91997-04-29 20:08:16 +00002255static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 {"__build_class__", (PyCFunction)builtin___build_class__,
2257 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2258 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2259 {"abs", builtin_abs, METH_O, abs_doc},
2260 {"all", builtin_all, METH_O, all_doc},
2261 {"any", builtin_any, METH_O, any_doc},
2262 {"ascii", builtin_ascii, METH_O, ascii_doc},
2263 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002264 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2266 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2267 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2268 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2269 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2270 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2271 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2272 {"format", builtin_format, METH_VARARGS, format_doc},
2273 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2274 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2275 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2276 {"hash", builtin_hash, METH_O, hash_doc},
2277 {"hex", builtin_hex, METH_O, hex_doc},
2278 {"id", builtin_id, METH_O, id_doc},
2279 {"input", builtin_input, METH_VARARGS, input_doc},
2280 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2281 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2282 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2283 {"len", builtin_len, METH_O, len_doc},
2284 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2285 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2286 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2287 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2288 {"oct", builtin_oct, METH_O, oct_doc},
2289 {"ord", builtin_ord, METH_O, ord_doc},
2290 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2291 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2292 {"repr", builtin_repr, METH_O, repr_doc},
2293 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2294 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2295 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2296 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2297 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2298 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002299};
2300
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002301PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002302"Built-in functions, exceptions, and other objects.\n\
2303\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002304Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002305
Martin v. Löwis1a214512008-06-11 05:26:20 +00002306static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 PyModuleDef_HEAD_INIT,
2308 "builtins",
2309 builtin_doc,
2310 -1, /* multiple "initialization" just copies the module dict. */
2311 builtin_methods,
2312 NULL,
2313 NULL,
2314 NULL,
2315 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002316};
2317
2318
Guido van Rossum25ce5661997-08-02 03:10:38 +00002319PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002320_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 PyObject *mod, *dict, *debug;
2323 mod = PyModule_Create(&builtinsmodule);
2324 if (mod == NULL)
2325 return NULL;
2326 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002327
Tim Peters7571a0f2003-03-23 17:52:28 +00002328#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 /* "builtins" exposes a number of statically allocated objects
2330 * that, before this code was added in 2.3, never showed up in
2331 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2332 * result, programs leaking references to None and False (etc)
2333 * couldn't be diagnosed by examining sys.getobjects(0).
2334 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002335#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2336#else
2337#define ADD_TO_ALL(OBJECT) (void)0
2338#endif
2339
Tim Peters4b7625e2001-09-13 21:37:17 +00002340#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2342 return NULL; \
2343 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 SETBUILTIN("None", Py_None);
2346 SETBUILTIN("Ellipsis", Py_Ellipsis);
2347 SETBUILTIN("NotImplemented", Py_NotImplemented);
2348 SETBUILTIN("False", Py_False);
2349 SETBUILTIN("True", Py_True);
2350 SETBUILTIN("bool", &PyBool_Type);
2351 SETBUILTIN("memoryview", &PyMemoryView_Type);
2352 SETBUILTIN("bytearray", &PyByteArray_Type);
2353 SETBUILTIN("bytes", &PyBytes_Type);
2354 SETBUILTIN("classmethod", &PyClassMethod_Type);
2355 SETBUILTIN("complex", &PyComplex_Type);
2356 SETBUILTIN("dict", &PyDict_Type);
2357 SETBUILTIN("enumerate", &PyEnum_Type);
2358 SETBUILTIN("filter", &PyFilter_Type);
2359 SETBUILTIN("float", &PyFloat_Type);
2360 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2361 SETBUILTIN("property", &PyProperty_Type);
2362 SETBUILTIN("int", &PyLong_Type);
2363 SETBUILTIN("list", &PyList_Type);
2364 SETBUILTIN("map", &PyMap_Type);
2365 SETBUILTIN("object", &PyBaseObject_Type);
2366 SETBUILTIN("range", &PyRange_Type);
2367 SETBUILTIN("reversed", &PyReversed_Type);
2368 SETBUILTIN("set", &PySet_Type);
2369 SETBUILTIN("slice", &PySlice_Type);
2370 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2371 SETBUILTIN("str", &PyUnicode_Type);
2372 SETBUILTIN("super", &PySuper_Type);
2373 SETBUILTIN("tuple", &PyTuple_Type);
2374 SETBUILTIN("type", &PyType_Type);
2375 SETBUILTIN("zip", &PyZip_Type);
2376 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2377 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2378 Py_XDECREF(debug);
2379 return NULL;
2380 }
2381 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002384#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002385#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002386}