blob: f374277f3dcb8a11dd2bb9d1a7381e17a2a993b0 [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 Rossum5b722181993-03-30 17:46:03 +00008#include "eval.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00009
Guido van Rossum6bf62da1997-04-11 20:37:35 +000010#include <ctype.h>
11
Victor Stinnerb744ba12010-05-15 12:27:16 +000012#ifdef HAVE_LANGINFO_H
13#include <langinfo.h> /* CODESET */
14#endif
15
Mark Hammond26cffde42001-05-14 12:17:34 +000016/* The default encoding used by the platform file system APIs
17 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000018
19 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
20 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000021*/
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000022#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Mark Hammond26cffde42001-05-14 12:17:34 +000023const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000024int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000025#elif defined(__APPLE__)
26const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000027int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerb744ba12010-05-15 12:27:16 +000028#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
29const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000030int Py_HasFileSystemDefaultEncoding = 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +000031#else
32const char *Py_FileSystemDefaultEncoding = "utf-8";
33int Py_HasFileSystemDefaultEncoding = 1;
Mark Hammond26cffde42001-05-14 12:17:34 +000034#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000035
Guido van Rossum79f25d91997-04-29 20:08:16 +000036static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000037builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
38{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell;
40 PyObject *cls = NULL;
41 Py_ssize_t nargs, nbases;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043 assert(args != NULL);
44 if (!PyTuple_Check(args)) {
45 PyErr_SetString(PyExc_TypeError,
46 "__build_class__: args is not a tuple");
47 return NULL;
48 }
49 nargs = PyTuple_GET_SIZE(args);
50 if (nargs < 2) {
51 PyErr_SetString(PyExc_TypeError,
52 "__build_class__: not enough arguments");
53 return NULL;
54 }
55 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
56 name = PyTuple_GET_ITEM(args, 1);
57 if (!PyUnicode_Check(name)) {
58 PyErr_SetString(PyExc_TypeError,
59 "__build_class__: name is not a string");
60 return NULL;
61 }
62 bases = PyTuple_GetSlice(args, 2, nargs);
63 if (bases == NULL)
64 return NULL;
65 nbases = nargs - 2;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 if (kwds == NULL) {
68 meta = NULL;
69 mkw = NULL;
70 }
71 else {
72 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
73 if (mkw == NULL) {
74 Py_DECREF(bases);
75 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000076 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 meta = PyDict_GetItemString(mkw, "metaclass");
78 if (meta != NULL) {
79 Py_INCREF(meta);
80 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
81 Py_DECREF(meta);
82 Py_DECREF(mkw);
83 Py_DECREF(bases);
84 return NULL;
85 }
86 }
87 }
88 if (meta == NULL) {
89 if (PyTuple_GET_SIZE(bases) == 0)
90 meta = (PyObject *) (&PyType_Type);
91 else {
92 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
93 meta = (PyObject *) (base0->ob_type);
94 }
95 Py_INCREF(meta);
96 }
97 prep = PyObject_GetAttrString(meta, "__prepare__");
98 if (prep == NULL) {
99 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
100 PyErr_Clear();
101 ns = PyDict_New();
102 }
103 else {
104 Py_DECREF(meta);
105 Py_XDECREF(mkw);
106 Py_DECREF(bases);
107 return NULL;
108 }
109 }
110 else {
111 PyObject *pargs = PyTuple_Pack(2, name, bases);
112 if (pargs == NULL) {
113 Py_DECREF(prep);
114 Py_DECREF(meta);
115 Py_XDECREF(mkw);
116 Py_DECREF(bases);
117 return NULL;
118 }
119 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
120 Py_DECREF(pargs);
121 Py_DECREF(prep);
122 }
123 if (ns == NULL) {
124 Py_DECREF(meta);
125 Py_XDECREF(mkw);
126 Py_DECREF(bases);
127 return NULL;
128 }
129 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
130 if (cell != NULL) {
131 PyObject *margs;
132 margs = PyTuple_Pack(3, name, bases, ns);
133 if (margs != NULL) {
134 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
135 Py_DECREF(margs);
136 }
137 if (cls != NULL && PyCell_Check(cell)) {
138 Py_INCREF(cls);
139 PyCell_SET(cell, cls);
140 }
141 Py_DECREF(cell);
142 }
143 Py_DECREF(ns);
144 Py_DECREF(meta);
145 Py_XDECREF(mkw);
146 Py_DECREF(bases);
147 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000148}
149
150PyDoc_STRVAR(build_class_doc,
151"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
152\n\
153Internal helper function used by the class statement.");
154
155static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000156builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
159 "level", 0};
160 char *name;
161 PyObject *globals = NULL;
162 PyObject *locals = NULL;
163 PyObject *fromlist = NULL;
164 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
167 kwlist, &name, &globals, &locals, &fromlist, &level))
168 return NULL;
169 return PyImport_ImportModuleLevel(name, globals, locals,
170 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000171}
172
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000173PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000174"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000175\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000176Import a module. Because this function is meant for use by the Python\n\
177interpreter and not for general use it is better to use\n\
178importlib.import_module() to programmatically import a module.\n\
179\n\
180The globals argument is only used to determine the context;\n\
181they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000182should be a list of names to emulate ``from name import ...'', or an\n\
183empty list to emulate ``import name''.\n\
184When importing a module from a package, note that __import__('A.B', ...)\n\
185returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000186fromlist is not empty. Level is used to determine whether to perform \n\
187absolute or relative imports. -1 is the original strategy of attempting\n\
188both absolute and relative imports, 0 is absolute, a positive number\n\
189is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000190
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000191
Guido van Rossum79f25d91997-04-29 20:08:16 +0000192static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000193builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000196}
197
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000198PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000199"abs(number) -> number\n\
200\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000201Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000202
Raymond Hettinger96229b12005-03-11 06:49:40 +0000203static PyObject *
204builtin_all(PyObject *self, PyObject *v)
205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 PyObject *it, *item;
207 PyObject *(*iternext)(PyObject *);
208 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 it = PyObject_GetIter(v);
211 if (it == NULL)
212 return NULL;
213 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 for (;;) {
216 item = iternext(it);
217 if (item == NULL)
218 break;
219 cmp = PyObject_IsTrue(item);
220 Py_DECREF(item);
221 if (cmp < 0) {
222 Py_DECREF(it);
223 return NULL;
224 }
225 if (cmp == 0) {
226 Py_DECREF(it);
227 Py_RETURN_FALSE;
228 }
229 }
230 Py_DECREF(it);
231 if (PyErr_Occurred()) {
232 if (PyErr_ExceptionMatches(PyExc_StopIteration))
233 PyErr_Clear();
234 else
235 return NULL;
236 }
237 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000238}
239
240PyDoc_STRVAR(all_doc,
241"all(iterable) -> bool\n\
242\n\
243Return True if bool(x) is True for all values x in the iterable.");
244
245static PyObject *
246builtin_any(PyObject *self, PyObject *v)
247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 PyObject *it, *item;
249 PyObject *(*iternext)(PyObject *);
250 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 it = PyObject_GetIter(v);
253 if (it == NULL)
254 return NULL;
255 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 for (;;) {
258 item = iternext(it);
259 if (item == NULL)
260 break;
261 cmp = PyObject_IsTrue(item);
262 Py_DECREF(item);
263 if (cmp < 0) {
264 Py_DECREF(it);
265 return NULL;
266 }
267 if (cmp == 1) {
268 Py_DECREF(it);
269 Py_RETURN_TRUE;
270 }
271 }
272 Py_DECREF(it);
273 if (PyErr_Occurred()) {
274 if (PyErr_ExceptionMatches(PyExc_StopIteration))
275 PyErr_Clear();
276 else
277 return NULL;
278 }
279 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000280}
281
282PyDoc_STRVAR(any_doc,
283"any(iterable) -> bool\n\
284\n\
285Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000286
Georg Brandl559e5d72008-06-11 18:37:52 +0000287static PyObject *
288builtin_ascii(PyObject *self, PyObject *v)
289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000291}
292
293PyDoc_STRVAR(ascii_doc,
294"ascii(object) -> string\n\
295\n\
296As repr(), return a string containing a printable representation of an\n\
297object, but escape the non-ASCII characters in the string returned by\n\
298repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
299to that returned by repr() in Python 2.");
300
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000301
Guido van Rossum79f25d91997-04-29 20:08:16 +0000302static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000303builtin_bin(PyObject *self, PyObject *v)
304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000306}
307
308PyDoc_STRVAR(bin_doc,
309"bin(number) -> string\n\
310\n\
311Return the binary representation of an integer or long integer.");
312
313
Antoine Pitroue71362d2010-11-27 22:00:11 +0000314static PyObject *
315builtin_callable(PyObject *self, PyObject *v)
316{
317 return PyBool_FromLong((long)PyCallable_Check(v));
318}
319
320PyDoc_STRVAR(callable_doc,
321"callable(object) -> bool\n\
322\n\
323Return whether the object is callable (i.e., some kind of function).\n\
324Note that classes are callable, as are instances of classes with a\n\
325__call__() method.");
326
327
Raymond Hettinger17301e92008-03-13 00:19:26 +0000328typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 PyObject_HEAD
330 PyObject *func;
331 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000332} filterobject;
333
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000334static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000335filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 PyObject *func, *seq;
338 PyObject *it;
339 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
342 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
345 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 /* Get iterator. */
348 it = PyObject_GetIter(seq);
349 if (it == NULL)
350 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 /* create filterobject structure */
353 lz = (filterobject *)type->tp_alloc(type, 0);
354 if (lz == NULL) {
355 Py_DECREF(it);
356 return NULL;
357 }
358 Py_INCREF(func);
359 lz->func = func;
360 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000363}
364
365static void
366filter_dealloc(filterobject *lz)
367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 PyObject_GC_UnTrack(lz);
369 Py_XDECREF(lz->func);
370 Py_XDECREF(lz->it);
371 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000372}
373
374static int
375filter_traverse(filterobject *lz, visitproc visit, void *arg)
376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 Py_VISIT(lz->it);
378 Py_VISIT(lz->func);
379 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000380}
381
382static PyObject *
383filter_next(filterobject *lz)
384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 PyObject *item;
386 PyObject *it = lz->it;
387 long ok;
388 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 iternext = *Py_TYPE(it)->tp_iternext;
391 for (;;) {
392 item = iternext(it);
393 if (item == NULL)
394 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
397 ok = PyObject_IsTrue(item);
398 } else {
399 PyObject *good;
400 good = PyObject_CallFunctionObjArgs(lz->func,
401 item, NULL);
402 if (good == NULL) {
403 Py_DECREF(item);
404 return NULL;
405 }
406 ok = PyObject_IsTrue(good);
407 Py_DECREF(good);
408 }
409 if (ok)
410 return item;
411 Py_DECREF(item);
412 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000413}
414
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000415PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000416"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000417\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000418Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000419is true. If function is None, return the items that are true.");
420
421PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 PyVarObject_HEAD_INIT(&PyType_Type, 0)
423 "filter", /* tp_name */
424 sizeof(filterobject), /* tp_basicsize */
425 0, /* tp_itemsize */
426 /* methods */
427 (destructor)filter_dealloc, /* tp_dealloc */
428 0, /* tp_print */
429 0, /* tp_getattr */
430 0, /* tp_setattr */
431 0, /* tp_reserved */
432 0, /* tp_repr */
433 0, /* tp_as_number */
434 0, /* tp_as_sequence */
435 0, /* tp_as_mapping */
436 0, /* tp_hash */
437 0, /* tp_call */
438 0, /* tp_str */
439 PyObject_GenericGetAttr, /* tp_getattro */
440 0, /* tp_setattro */
441 0, /* tp_as_buffer */
442 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
443 Py_TPFLAGS_BASETYPE, /* tp_flags */
444 filter_doc, /* tp_doc */
445 (traverseproc)filter_traverse, /* tp_traverse */
446 0, /* tp_clear */
447 0, /* tp_richcompare */
448 0, /* tp_weaklistoffset */
449 PyObject_SelfIter, /* tp_iter */
450 (iternextfunc)filter_next, /* tp_iternext */
451 0, /* tp_methods */
452 0, /* tp_members */
453 0, /* tp_getset */
454 0, /* tp_base */
455 0, /* tp_dict */
456 0, /* tp_descr_get */
457 0, /* tp_descr_set */
458 0, /* tp_dictoffset */
459 0, /* tp_init */
460 PyType_GenericAlloc, /* tp_alloc */
461 filter_new, /* tp_new */
462 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000463};
464
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000465
Eric Smith8c663262007-08-25 02:26:07 +0000466static PyObject *
467builtin_format(PyObject *self, PyObject *args)
468{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000469 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000470 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000471
Eric Smith8fd3eba2008-02-17 19:48:00 +0000472 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000474
Eric Smith8fd3eba2008-02-17 19:48:00 +0000475 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000476}
477
Eric Smith8c663262007-08-25 02:26:07 +0000478PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000479"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000480\n\
Eric Smith81936692007-08-31 01:14:01 +0000481Returns value.__format__(format_spec)\n\
482format_spec defaults to \"\"");
483
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000484static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000485builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 if (!PyArg_ParseTuple(args, "i:chr", &x))
490 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000493}
494
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000495PyDoc_VAR(chr_doc) = PyDoc_STR(
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000496"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000497\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000498Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000499)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000500#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000501PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000502"\nIf 0x10000 <= i, a surrogate pair is returned."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000503)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000504#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000505;
Guido van Rossum09095f32000-03-10 23:00:52 +0000506
507
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000508static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000509source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 char *str;
512 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 if (PyUnicode_Check(cmd)) {
515 cf->cf_flags |= PyCF_IGNORE_COOKIE;
516 cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL);
517 if (cmd == NULL)
518 return NULL;
519 }
520 else if (!PyObject_CheckReadBuffer(cmd)) {
521 PyErr_Format(PyExc_TypeError,
522 "%s() arg 1 must be a %s object",
523 funcname, what);
524 return NULL;
525 }
526 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
527 return NULL;
528 }
529 if (strlen(str) != size) {
530 PyErr_SetString(PyExc_TypeError,
531 "source code string cannot contain null bytes");
532 return NULL;
533 }
534 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000535}
536
Guido van Rossum79f25d91997-04-29 20:08:16 +0000537static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000538builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 char *str;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000541 PyObject *filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 char *filename;
543 char *startstr;
544 int mode = -1;
545 int dont_inherit = 0;
546 int supplied_flags = 0;
547 int is_ast;
548 PyCompilerFlags cf;
549 PyObject *cmd;
550 static char *kwlist[] = {"source", "filename", "mode", "flags",
551 "dont_inherit", NULL};
552 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000553 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000554
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000555 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|ii:compile", kwlist,
556 &cmd,
557 PyUnicode_FSConverter, &filename_obj,
558 &startstr, &supplied_flags,
559 &dont_inherit))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000561
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000562 filename = PyBytes_AS_STRING(filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 if (supplied_flags &
566 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
567 {
568 PyErr_SetString(PyExc_ValueError,
569 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000570 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 }
572 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 if (!dont_inherit) {
575 PyEval_MergeCompilerFlags(&cf);
576 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 if (strcmp(startstr, "exec") == 0)
579 mode = 0;
580 else if (strcmp(startstr, "eval") == 0)
581 mode = 1;
582 else if (strcmp(startstr, "single") == 0)
583 mode = 2;
584 else {
585 PyErr_SetString(PyExc_ValueError,
586 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000587 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 is_ast = PyAST_Check(cmd);
591 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000592 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 if (supplied_flags & PyCF_ONLY_AST) {
595 Py_INCREF(cmd);
596 result = cmd;
597 }
598 else {
599 PyArena *arena;
600 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 arena = PyArena_New();
603 mod = PyAST_obj2mod(cmd, arena, mode);
604 if (mod == NULL) {
605 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000606 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 }
608 result = (PyObject*)PyAST_Compile(mod, filename,
609 &cf, arena);
610 PyArena_Free(arena);
611 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000612 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
616 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000617 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000618
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000619 result = Py_CompileStringFlags(str, filename, start[mode], &cf);
620 goto finally;
621
622error:
623 result = NULL;
624finally:
625 Py_DECREF(filename_obj);
626 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000627}
628
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000629PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000630"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000631\n\
632Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000633into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000634The filename will be used for run-time error messages.\n\
635The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000636single (interactive) statement, or 'eval' to compile an expression.\n\
637The flags argument, if present, controls which future statements influence\n\
638the compilation of the code.\n\
639The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
640the effects of any future statements in effect in the code calling\n\
641compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000642in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000643
Guido van Rossum79f25d91997-04-29 20:08:16 +0000644static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000645builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
650 return NULL;
651 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000652}
653
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000654PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000655"dir([object]) -> list of strings\n"
656"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000657"If called without an argument, return the names in the current scope.\n"
658"Else, return an alphabetized list of names comprising (some of) the attributes\n"
659"of the given object, and of attributes reachable from it.\n"
660"If the object supplies a method named __dir__, it will be used; otherwise\n"
661"the default dir() logic is used and returns:\n"
662" for a module object: the module's attributes.\n"
663" for a class object: its attributes, and recursively the attributes\n"
664" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000665" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000666" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000667
Guido van Rossum79f25d91997-04-29 20:08:16 +0000668static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000669builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
674 return NULL;
675 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000676}
677
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000678PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000679"divmod(x, y) -> (div, mod)\n\
680\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000681Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000682
683
Guido van Rossum79f25d91997-04-29 20:08:16 +0000684static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000685builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 PyObject *cmd, *result, *tmp = NULL;
688 PyObject *globals = Py_None, *locals = Py_None;
689 char *str;
690 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
693 return NULL;
694 if (locals != Py_None && !PyMapping_Check(locals)) {
695 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
696 return NULL;
697 }
698 if (globals != Py_None && !PyDict_Check(globals)) {
699 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
700 "globals must be a real dict; try eval(expr, {}, mapping)"
701 : "globals must be a dict");
702 return NULL;
703 }
704 if (globals == Py_None) {
705 globals = PyEval_GetGlobals();
706 if (locals == Py_None)
707 locals = PyEval_GetLocals();
708 }
709 else if (locals == Py_None)
710 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 if (globals == NULL || locals == NULL) {
713 PyErr_SetString(PyExc_TypeError,
714 "eval must be given globals and locals "
715 "when called without a frame");
716 return NULL;
717 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
720 if (PyDict_SetItemString(globals, "__builtins__",
721 PyEval_GetBuiltins()) != 0)
722 return NULL;
723 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 if (PyCode_Check(cmd)) {
726 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
727 PyErr_SetString(PyExc_TypeError,
728 "code object passed to eval() may not contain free variables");
729 return NULL;
730 }
731 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
732 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
735 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
736 if (str == NULL)
737 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 while (*str == ' ' || *str == '\t')
740 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 (void)PyEval_MergeCompilerFlags(&cf);
743 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
744 Py_XDECREF(tmp);
745 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000746}
747
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000748PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000749"eval(source[, globals[, locals]]) -> value\n\
750\n\
751Evaluate the source in the context of globals and locals.\n\
752The source may be a string representing a Python expression\n\
753or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000754The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000755defaulting to the current globals and locals.\n\
756If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000757
Georg Brandl7cae87c2006-09-06 06:51:57 +0000758static PyObject *
759builtin_exec(PyObject *self, PyObject *args)
760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 PyObject *v;
762 PyObject *prog, *globals = Py_None, *locals = Py_None;
763 int plain = 0;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
766 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 if (globals == Py_None) {
769 globals = PyEval_GetGlobals();
770 if (locals == Py_None) {
771 locals = PyEval_GetLocals();
772 plain = 1;
773 }
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 }
807 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
808 }
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;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1620 if (!stdin_encoding)
1621 /* stdin is a text stream, so it must have an
1622 encoding. */
1623 return NULL;
Victor Stinner306f0102010-05-19 01:06:22 +00001624 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
1625 if (stdin_encoding_str == NULL) {
1626 Py_DECREF(stdin_encoding);
1627 return NULL;
1628 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 tmp = PyObject_CallMethod(fout, "flush", "");
1630 if (tmp == NULL)
1631 PyErr_Clear();
1632 else
1633 Py_DECREF(tmp);
1634 if (promptarg != NULL) {
1635 PyObject *stringpo;
1636 PyObject *stdout_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001637 char *stdout_encoding_str;
1638 stdout_encoding = PyObject_GetAttrString(fout, "encoding");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 if (stdout_encoding == NULL) {
1640 Py_DECREF(stdin_encoding);
1641 return NULL;
1642 }
Victor Stinner306f0102010-05-19 01:06:22 +00001643 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
1644 if (stdout_encoding_str == NULL) {
1645 Py_DECREF(stdin_encoding);
1646 Py_DECREF(stdout_encoding);
1647 return NULL;
1648 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 stringpo = PyObject_Str(promptarg);
1650 if (stringpo == NULL) {
1651 Py_DECREF(stdin_encoding);
1652 Py_DECREF(stdout_encoding);
1653 return NULL;
1654 }
1655 po = PyUnicode_AsEncodedString(stringpo,
Victor Stinner306f0102010-05-19 01:06:22 +00001656 stdout_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 Py_DECREF(stdout_encoding);
1658 Py_DECREF(stringpo);
1659 if (po == NULL) {
1660 Py_DECREF(stdin_encoding);
1661 return NULL;
1662 }
1663 prompt = PyBytes_AsString(po);
1664 if (prompt == NULL) {
1665 Py_DECREF(stdin_encoding);
1666 Py_DECREF(po);
1667 return NULL;
1668 }
1669 }
1670 else {
1671 po = NULL;
1672 prompt = "";
1673 }
1674 s = PyOS_Readline(stdin, stdout, prompt);
1675 Py_XDECREF(po);
1676 if (s == NULL) {
1677 if (!PyErr_Occurred())
1678 PyErr_SetNone(PyExc_KeyboardInterrupt);
1679 Py_DECREF(stdin_encoding);
1680 return NULL;
1681 }
1682 if (*s == '\0') {
1683 PyErr_SetNone(PyExc_EOFError);
1684 result = NULL;
1685 }
1686 else { /* strip trailing '\n' */
1687 size_t len = strlen(s);
1688 if (len > PY_SSIZE_T_MAX) {
1689 PyErr_SetString(PyExc_OverflowError,
1690 "input: input too long");
1691 result = NULL;
1692 }
1693 else {
Victor Stinner306f0102010-05-19 01:06:22 +00001694 result = PyUnicode_Decode(s, len-1, stdin_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 }
1696 }
1697 Py_DECREF(stdin_encoding);
1698 PyMem_FREE(s);
1699 return result;
1700 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 /* Fallback if we're not interactive */
1703 if (promptarg != NULL) {
1704 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1705 return NULL;
1706 }
1707 tmp = PyObject_CallMethod(fout, "flush", "");
1708 if (tmp == NULL)
1709 PyErr_Clear();
1710 else
1711 Py_DECREF(tmp);
1712 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001713}
1714
1715PyDoc_STRVAR(input_doc,
1716"input([prompt]) -> string\n\
1717\n\
1718Read a string from standard input. The trailing newline is stripped.\n\
1719If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1720On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1721is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001722
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001723
Guido van Rossum79f25d91997-04-29 20:08:16 +00001724static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001725builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001728}
1729
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001730PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001731"repr(object) -> string\n\
1732\n\
1733Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001734For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001735
1736
Guido van Rossum79f25d91997-04-29 20:08:16 +00001737static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001738builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 static PyObject *round_str = NULL;
1741 PyObject *ndigits = NULL;
1742 static char *kwlist[] = {"number", "ndigits", 0};
1743 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1746 kwlist, &number, &ndigits))
1747 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 if (Py_TYPE(number)->tp_dict == NULL) {
1750 if (PyType_Ready(Py_TYPE(number)) < 0)
1751 return NULL;
1752 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 if (round_str == NULL) {
1755 round_str = PyUnicode_InternFromString("__round__");
1756 if (round_str == NULL)
1757 return NULL;
1758 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 round = _PyType_Lookup(Py_TYPE(number), round_str);
1761 if (round == NULL) {
1762 PyErr_Format(PyExc_TypeError,
1763 "type %.100s doesn't define __round__ method",
1764 Py_TYPE(number)->tp_name);
1765 return NULL;
1766 }
Alex Martelliae211f92007-08-22 23:21:33 +00001767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 if (ndigits == NULL)
1769 return PyObject_CallFunction(round, "O", number);
1770 else
1771 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001772}
1773
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001774PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001775"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001776\n\
1777Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001778This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001779same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001780
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001781
Raymond Hettinger64958a12003-12-17 20:43:33 +00001782static PyObject *
1783builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1786 PyObject *callable;
1787 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1788 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 /* args 1-3 should match listsort in Objects/listobject.c */
1791 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1792 kwlist, &seq, &keyfunc, &reverse))
1793 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 newlist = PySequence_List(seq);
1796 if (newlist == NULL)
1797 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 callable = PyObject_GetAttrString(newlist, "sort");
1800 if (callable == NULL) {
1801 Py_DECREF(newlist);
1802 return NULL;
1803 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 newargs = PyTuple_GetSlice(args, 1, 4);
1806 if (newargs == NULL) {
1807 Py_DECREF(newlist);
1808 Py_DECREF(callable);
1809 return NULL;
1810 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 v = PyObject_Call(callable, newargs, kwds);
1813 Py_DECREF(newargs);
1814 Py_DECREF(callable);
1815 if (v == NULL) {
1816 Py_DECREF(newlist);
1817 return NULL;
1818 }
1819 Py_DECREF(v);
1820 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001821}
1822
1823PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001824"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001825
Guido van Rossum79f25d91997-04-29 20:08:16 +00001826static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001827builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 PyObject *v = NULL;
1830 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1833 return NULL;
1834 if (v == NULL) {
1835 d = PyEval_GetLocals();
1836 if (d == NULL) {
1837 if (!PyErr_Occurred())
1838 PyErr_SetString(PyExc_SystemError,
1839 "vars(): no locals!?");
1840 }
1841 else
1842 Py_INCREF(d);
1843 }
1844 else {
1845 d = PyObject_GetAttrString(v, "__dict__");
1846 if (d == NULL) {
1847 PyErr_SetString(PyExc_TypeError,
1848 "vars() argument must have __dict__ attribute");
1849 return NULL;
1850 }
1851 }
1852 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001853}
1854
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001855PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001856"vars([object]) -> dictionary\n\
1857\n\
1858Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001859With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001860
Alex Martellia70b1912003-04-22 08:12:33 +00001861static PyObject*
1862builtin_sum(PyObject *self, PyObject *args)
1863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 PyObject *seq;
1865 PyObject *result = NULL;
1866 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1869 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 iter = PyObject_GetIter(seq);
1872 if (iter == NULL)
1873 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 if (result == NULL) {
1876 result = PyLong_FromLong(0);
1877 if (result == NULL) {
1878 Py_DECREF(iter);
1879 return NULL;
1880 }
1881 } else {
1882 /* reject string values for 'start' parameter */
1883 if (PyUnicode_Check(result)) {
1884 PyErr_SetString(PyExc_TypeError,
1885 "sum() can't sum strings [use ''.join(seq) instead]");
1886 Py_DECREF(iter);
1887 return NULL;
1888 }
1889 if (PyByteArray_Check(result)) {
1890 PyErr_SetString(PyExc_TypeError,
1891 "sum() can't sum bytes [use b''.join(seq) instead]");
1892 Py_DECREF(iter);
1893 return NULL;
1894 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 Py_INCREF(result);
1897 }
Alex Martellia70b1912003-04-22 08:12:33 +00001898
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001899#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1901 Assumes all inputs are the same type. If the assumption fails, default
1902 to the more general routine.
1903 */
1904 if (PyLong_CheckExact(result)) {
1905 int overflow;
1906 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1907 /* If this already overflowed, don't even enter the loop. */
1908 if (overflow == 0) {
1909 Py_DECREF(result);
1910 result = NULL;
1911 }
1912 while(result == NULL) {
1913 item = PyIter_Next(iter);
1914 if (item == NULL) {
1915 Py_DECREF(iter);
1916 if (PyErr_Occurred())
1917 return NULL;
1918 return PyLong_FromLong(i_result);
1919 }
1920 if (PyLong_CheckExact(item)) {
1921 long b = PyLong_AsLongAndOverflow(item, &overflow);
1922 long x = i_result + b;
1923 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1924 i_result = x;
1925 Py_DECREF(item);
1926 continue;
1927 }
1928 }
1929 /* Either overflowed or is not an int. Restore real objects and process normally */
1930 result = PyLong_FromLong(i_result);
1931 temp = PyNumber_Add(result, item);
1932 Py_DECREF(result);
1933 Py_DECREF(item);
1934 result = temp;
1935 if (result == NULL) {
1936 Py_DECREF(iter);
1937 return NULL;
1938 }
1939 }
1940 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 if (PyFloat_CheckExact(result)) {
1943 double f_result = PyFloat_AS_DOUBLE(result);
1944 Py_DECREF(result);
1945 result = NULL;
1946 while(result == NULL) {
1947 item = PyIter_Next(iter);
1948 if (item == NULL) {
1949 Py_DECREF(iter);
1950 if (PyErr_Occurred())
1951 return NULL;
1952 return PyFloat_FromDouble(f_result);
1953 }
1954 if (PyFloat_CheckExact(item)) {
1955 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1956 f_result += PyFloat_AS_DOUBLE(item);
1957 PyFPE_END_PROTECT(f_result)
1958 Py_DECREF(item);
1959 continue;
1960 }
1961 if (PyLong_CheckExact(item)) {
1962 long value;
1963 int overflow;
1964 value = PyLong_AsLongAndOverflow(item, &overflow);
1965 if (!overflow) {
1966 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1967 f_result += (double)value;
1968 PyFPE_END_PROTECT(f_result)
1969 Py_DECREF(item);
1970 continue;
1971 }
1972 }
1973 result = PyFloat_FromDouble(f_result);
1974 temp = PyNumber_Add(result, item);
1975 Py_DECREF(result);
1976 Py_DECREF(item);
1977 result = temp;
1978 if (result == NULL) {
1979 Py_DECREF(iter);
1980 return NULL;
1981 }
1982 }
1983 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001984#endif
1985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 for(;;) {
1987 item = PyIter_Next(iter);
1988 if (item == NULL) {
1989 /* error, or end-of-sequence */
1990 if (PyErr_Occurred()) {
1991 Py_DECREF(result);
1992 result = NULL;
1993 }
1994 break;
1995 }
1996 /* It's tempting to use PyNumber_InPlaceAdd instead of
1997 PyNumber_Add here, to avoid quadratic running time
1998 when doing 'sum(list_of_lists, [])'. However, this
1999 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 empty = []
2002 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 would change the value of empty. */
2005 temp = PyNumber_Add(result, item);
2006 Py_DECREF(result);
2007 Py_DECREF(item);
2008 result = temp;
2009 if (result == NULL)
2010 break;
2011 }
2012 Py_DECREF(iter);
2013 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002014}
2015
2016PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002017"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002018\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002019Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2020of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002021empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002022
2023
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002024static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002025builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 PyObject *inst;
2028 PyObject *cls;
2029 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2032 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 retval = PyObject_IsInstance(inst, cls);
2035 if (retval < 0)
2036 return NULL;
2037 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002038}
2039
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002040PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002041"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002042\n\
2043Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002044With a type as second argument, return whether that is the object's type.\n\
2045The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002046isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002047
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002048
2049static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002050builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 PyObject *derived;
2053 PyObject *cls;
2054 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2057 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 retval = PyObject_IsSubclass(derived, cls);
2060 if (retval < 0)
2061 return NULL;
2062 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002063}
2064
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002065PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002066"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002067\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002068Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2069When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2070is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002071
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002072
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002073typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 PyObject_HEAD
2075 Py_ssize_t tuplesize;
2076 PyObject *ittuple; /* tuple of iterators */
2077 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002078} zipobject;
2079
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002080static PyObject *
2081zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 zipobject *lz;
2084 Py_ssize_t i;
2085 PyObject *ittuple; /* tuple of iterators */
2086 PyObject *result;
2087 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2090 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 /* args must be a tuple */
2093 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 /* obtain iterators */
2096 ittuple = PyTuple_New(tuplesize);
2097 if (ittuple == NULL)
2098 return NULL;
2099 for (i=0; i < tuplesize; ++i) {
2100 PyObject *item = PyTuple_GET_ITEM(args, i);
2101 PyObject *it = PyObject_GetIter(item);
2102 if (it == NULL) {
2103 if (PyErr_ExceptionMatches(PyExc_TypeError))
2104 PyErr_Format(PyExc_TypeError,
2105 "zip argument #%zd must support iteration",
2106 i+1);
2107 Py_DECREF(ittuple);
2108 return NULL;
2109 }
2110 PyTuple_SET_ITEM(ittuple, i, it);
2111 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 /* create a result holder */
2114 result = PyTuple_New(tuplesize);
2115 if (result == NULL) {
2116 Py_DECREF(ittuple);
2117 return NULL;
2118 }
2119 for (i=0 ; i < tuplesize ; i++) {
2120 Py_INCREF(Py_None);
2121 PyTuple_SET_ITEM(result, i, Py_None);
2122 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 /* create zipobject structure */
2125 lz = (zipobject *)type->tp_alloc(type, 0);
2126 if (lz == NULL) {
2127 Py_DECREF(ittuple);
2128 Py_DECREF(result);
2129 return NULL;
2130 }
2131 lz->ittuple = ittuple;
2132 lz->tuplesize = tuplesize;
2133 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002136}
2137
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002138static void
2139zip_dealloc(zipobject *lz)
2140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 PyObject_GC_UnTrack(lz);
2142 Py_XDECREF(lz->ittuple);
2143 Py_XDECREF(lz->result);
2144 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002145}
2146
2147static int
2148zip_traverse(zipobject *lz, visitproc visit, void *arg)
2149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 Py_VISIT(lz->ittuple);
2151 Py_VISIT(lz->result);
2152 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002153}
2154
2155static PyObject *
2156zip_next(zipobject *lz)
2157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 Py_ssize_t i;
2159 Py_ssize_t tuplesize = lz->tuplesize;
2160 PyObject *result = lz->result;
2161 PyObject *it;
2162 PyObject *item;
2163 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 if (tuplesize == 0)
2166 return NULL;
2167 if (Py_REFCNT(result) == 1) {
2168 Py_INCREF(result);
2169 for (i=0 ; i < tuplesize ; i++) {
2170 it = PyTuple_GET_ITEM(lz->ittuple, i);
2171 item = (*Py_TYPE(it)->tp_iternext)(it);
2172 if (item == NULL) {
2173 Py_DECREF(result);
2174 return NULL;
2175 }
2176 olditem = PyTuple_GET_ITEM(result, i);
2177 PyTuple_SET_ITEM(result, i, item);
2178 Py_DECREF(olditem);
2179 }
2180 } else {
2181 result = PyTuple_New(tuplesize);
2182 if (result == NULL)
2183 return NULL;
2184 for (i=0 ; i < tuplesize ; i++) {
2185 it = PyTuple_GET_ITEM(lz->ittuple, i);
2186 item = (*Py_TYPE(it)->tp_iternext)(it);
2187 if (item == NULL) {
2188 Py_DECREF(result);
2189 return NULL;
2190 }
2191 PyTuple_SET_ITEM(result, i, item);
2192 }
2193 }
2194 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002195}
Barry Warsawbd599b52000-08-03 15:45:29 +00002196
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002197PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002198"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002199\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002200Return a zip object whose .__next__() method returns a tuple where\n\
2201the i-th element comes from the i-th iterable argument. The .__next__()\n\
2202method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002203is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002204
2205PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2207 "zip", /* tp_name */
2208 sizeof(zipobject), /* tp_basicsize */
2209 0, /* tp_itemsize */
2210 /* methods */
2211 (destructor)zip_dealloc, /* tp_dealloc */
2212 0, /* tp_print */
2213 0, /* tp_getattr */
2214 0, /* tp_setattr */
2215 0, /* tp_reserved */
2216 0, /* tp_repr */
2217 0, /* tp_as_number */
2218 0, /* tp_as_sequence */
2219 0, /* tp_as_mapping */
2220 0, /* tp_hash */
2221 0, /* tp_call */
2222 0, /* tp_str */
2223 PyObject_GenericGetAttr, /* tp_getattro */
2224 0, /* tp_setattro */
2225 0, /* tp_as_buffer */
2226 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2227 Py_TPFLAGS_BASETYPE, /* tp_flags */
2228 zip_doc, /* tp_doc */
2229 (traverseproc)zip_traverse, /* tp_traverse */
2230 0, /* tp_clear */
2231 0, /* tp_richcompare */
2232 0, /* tp_weaklistoffset */
2233 PyObject_SelfIter, /* tp_iter */
2234 (iternextfunc)zip_next, /* tp_iternext */
2235 0, /* tp_methods */
2236 0, /* tp_members */
2237 0, /* tp_getset */
2238 0, /* tp_base */
2239 0, /* tp_dict */
2240 0, /* tp_descr_get */
2241 0, /* tp_descr_set */
2242 0, /* tp_dictoffset */
2243 0, /* tp_init */
2244 PyType_GenericAlloc, /* tp_alloc */
2245 zip_new, /* tp_new */
2246 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002247};
Barry Warsawbd599b52000-08-03 15:45:29 +00002248
2249
Guido van Rossum79f25d91997-04-29 20:08:16 +00002250static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 {"__build_class__", (PyCFunction)builtin___build_class__,
2252 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2253 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2254 {"abs", builtin_abs, METH_O, abs_doc},
2255 {"all", builtin_all, METH_O, all_doc},
2256 {"any", builtin_any, METH_O, any_doc},
2257 {"ascii", builtin_ascii, METH_O, ascii_doc},
2258 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002259 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2261 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2262 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2263 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2264 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2265 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2266 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2267 {"format", builtin_format, METH_VARARGS, format_doc},
2268 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2269 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2270 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2271 {"hash", builtin_hash, METH_O, hash_doc},
2272 {"hex", builtin_hex, METH_O, hex_doc},
2273 {"id", builtin_id, METH_O, id_doc},
2274 {"input", builtin_input, METH_VARARGS, input_doc},
2275 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2276 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2277 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2278 {"len", builtin_len, METH_O, len_doc},
2279 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2280 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2281 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2282 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2283 {"oct", builtin_oct, METH_O, oct_doc},
2284 {"ord", builtin_ord, METH_O, ord_doc},
2285 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2286 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2287 {"repr", builtin_repr, METH_O, repr_doc},
2288 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2289 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2290 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2291 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2292 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2293 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002294};
2295
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002296PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002297"Built-in functions, exceptions, and other objects.\n\
2298\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002299Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002300
Martin v. Löwis1a214512008-06-11 05:26:20 +00002301static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 PyModuleDef_HEAD_INIT,
2303 "builtins",
2304 builtin_doc,
2305 -1, /* multiple "initialization" just copies the module dict. */
2306 builtin_methods,
2307 NULL,
2308 NULL,
2309 NULL,
2310 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002311};
2312
2313
Guido van Rossum25ce5661997-08-02 03:10:38 +00002314PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002315_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 PyObject *mod, *dict, *debug;
2318 mod = PyModule_Create(&builtinsmodule);
2319 if (mod == NULL)
2320 return NULL;
2321 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002322
Tim Peters7571a0f2003-03-23 17:52:28 +00002323#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 /* "builtins" exposes a number of statically allocated objects
2325 * that, before this code was added in 2.3, never showed up in
2326 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2327 * result, programs leaking references to None and False (etc)
2328 * couldn't be diagnosed by examining sys.getobjects(0).
2329 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002330#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2331#else
2332#define ADD_TO_ALL(OBJECT) (void)0
2333#endif
2334
Tim Peters4b7625e2001-09-13 21:37:17 +00002335#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2337 return NULL; \
2338 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 SETBUILTIN("None", Py_None);
2341 SETBUILTIN("Ellipsis", Py_Ellipsis);
2342 SETBUILTIN("NotImplemented", Py_NotImplemented);
2343 SETBUILTIN("False", Py_False);
2344 SETBUILTIN("True", Py_True);
2345 SETBUILTIN("bool", &PyBool_Type);
2346 SETBUILTIN("memoryview", &PyMemoryView_Type);
2347 SETBUILTIN("bytearray", &PyByteArray_Type);
2348 SETBUILTIN("bytes", &PyBytes_Type);
2349 SETBUILTIN("classmethod", &PyClassMethod_Type);
2350 SETBUILTIN("complex", &PyComplex_Type);
2351 SETBUILTIN("dict", &PyDict_Type);
2352 SETBUILTIN("enumerate", &PyEnum_Type);
2353 SETBUILTIN("filter", &PyFilter_Type);
2354 SETBUILTIN("float", &PyFloat_Type);
2355 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2356 SETBUILTIN("property", &PyProperty_Type);
2357 SETBUILTIN("int", &PyLong_Type);
2358 SETBUILTIN("list", &PyList_Type);
2359 SETBUILTIN("map", &PyMap_Type);
2360 SETBUILTIN("object", &PyBaseObject_Type);
2361 SETBUILTIN("range", &PyRange_Type);
2362 SETBUILTIN("reversed", &PyReversed_Type);
2363 SETBUILTIN("set", &PySet_Type);
2364 SETBUILTIN("slice", &PySlice_Type);
2365 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2366 SETBUILTIN("str", &PyUnicode_Type);
2367 SETBUILTIN("super", &PySuper_Type);
2368 SETBUILTIN("tuple", &PyTuple_Type);
2369 SETBUILTIN("type", &PyType_Type);
2370 SETBUILTIN("zip", &PyZip_Type);
2371 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2372 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2373 Py_XDECREF(debug);
2374 return NULL;
2375 }
2376 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002379#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002380#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002381}