blob: 3e44aa0566f63d53f8dad64d3472afb70b1df480 [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
Mark Hammond26cffde42001-05-14 12:17:34 +000012/* The default encoding used by the platform file system APIs
13 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000014
15 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
16 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000017*/
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000018#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Mark Hammond26cffde42001-05-14 12:17:34 +000019const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000020int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000021#elif defined(__APPLE__)
22const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000023int Py_HasFileSystemDefaultEncoding = 1;
Mark Hammond26cffde42001-05-14 12:17:34 +000024#else
25const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000027#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000028
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int
30_Py_SetFileSystemEncoding(PyObject *s)
31{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000032 PyObject *defenc, *codec;
33 if (!PyUnicode_Check(s)) {
34 PyErr_BadInternalCall();
35 return -1;
36 }
37 defenc = _PyUnicode_AsDefaultEncodedString(s, NULL);
38 if (!defenc)
39 return -1;
40 codec = _PyCodec_Lookup(PyBytes_AsString(defenc));
41 if (codec == NULL)
42 return -1;
43 Py_DECREF(codec);
44 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding)
45 /* A file system encoding was set at run-time */
46 free((char*)Py_FileSystemDefaultEncoding);
47 Py_FileSystemDefaultEncoding = strdup(PyBytes_AsString(defenc));
48 Py_HasFileSystemDefaultEncoding = 0;
49 return 0;
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000050}
51
Guido van Rossum79f25d91997-04-29 20:08:16 +000052static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000053builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
54{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000055 PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell;
56 PyObject *cls = NULL;
57 Py_ssize_t nargs, nbases;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000058
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000059 assert(args != NULL);
60 if (!PyTuple_Check(args)) {
61 PyErr_SetString(PyExc_TypeError,
62 "__build_class__: args is not a tuple");
63 return NULL;
64 }
65 nargs = PyTuple_GET_SIZE(args);
66 if (nargs < 2) {
67 PyErr_SetString(PyExc_TypeError,
68 "__build_class__: not enough arguments");
69 return NULL;
70 }
71 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
72 name = PyTuple_GET_ITEM(args, 1);
73 if (!PyUnicode_Check(name)) {
74 PyErr_SetString(PyExc_TypeError,
75 "__build_class__: name is not a string");
76 return NULL;
77 }
78 bases = PyTuple_GetSlice(args, 2, nargs);
79 if (bases == NULL)
80 return NULL;
81 nbases = nargs - 2;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000082
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000083 if (kwds == NULL) {
84 meta = NULL;
85 mkw = NULL;
86 }
87 else {
88 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
89 if (mkw == NULL) {
90 Py_DECREF(bases);
91 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000092 }
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000093 meta = PyDict_GetItemString(mkw, "metaclass");
94 if (meta != NULL) {
95 Py_INCREF(meta);
96 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
97 Py_DECREF(meta);
98 Py_DECREF(mkw);
99 Py_DECREF(bases);
100 return NULL;
101 }
102 }
103 }
104 if (meta == NULL) {
105 if (PyTuple_GET_SIZE(bases) == 0)
106 meta = (PyObject *) (&PyType_Type);
107 else {
108 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
109 meta = (PyObject *) (base0->ob_type);
110 }
111 Py_INCREF(meta);
112 }
113 prep = PyObject_GetAttrString(meta, "__prepare__");
114 if (prep == NULL) {
115 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
116 PyErr_Clear();
117 ns = PyDict_New();
118 }
119 else {
120 Py_DECREF(meta);
121 Py_XDECREF(mkw);
122 Py_DECREF(bases);
123 return NULL;
124 }
125 }
126 else {
127 PyObject *pargs = PyTuple_Pack(2, name, bases);
128 if (pargs == NULL) {
129 Py_DECREF(prep);
130 Py_DECREF(meta);
131 Py_XDECREF(mkw);
132 Py_DECREF(bases);
133 return NULL;
134 }
135 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
136 Py_DECREF(pargs);
137 Py_DECREF(prep);
138 }
139 if (ns == NULL) {
140 Py_DECREF(meta);
141 Py_XDECREF(mkw);
142 Py_DECREF(bases);
143 return NULL;
144 }
145 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
146 if (cell != NULL) {
147 PyObject *margs;
148 margs = PyTuple_Pack(3, name, bases, ns);
149 if (margs != NULL) {
150 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
151 Py_DECREF(margs);
152 }
153 if (cls != NULL && PyCell_Check(cell)) {
154 Py_INCREF(cls);
155 PyCell_SET(cell, cls);
156 }
157 Py_DECREF(cell);
158 }
159 Py_DECREF(ns);
160 Py_DECREF(meta);
161 Py_XDECREF(mkw);
162 Py_DECREF(bases);
163 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000164}
165
166PyDoc_STRVAR(build_class_doc,
167"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
168\n\
169Internal helper function used by the class statement.");
170
171static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000172builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000173{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000174 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
175 "level", 0};
176 char *name;
177 PyObject *globals = NULL;
178 PyObject *locals = NULL;
179 PyObject *fromlist = NULL;
180 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000181
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000182 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
183 kwlist, &name, &globals, &locals, &fromlist, &level))
184 return NULL;
185 return PyImport_ImportModuleLevel(name, globals, locals,
186 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000187}
188
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000189PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000190"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000191\n\
192Import a module. The globals are only used to determine the context;\n\
193they are not modified. The locals are currently unused. The fromlist\n\
194should be a list of names to emulate ``from name import ...'', or an\n\
195empty list to emulate ``import name''.\n\
196When importing a module from a package, note that __import__('A.B', ...)\n\
197returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000198fromlist is not empty. Level is used to determine whether to perform \n\
199absolute or relative imports. -1 is the original strategy of attempting\n\
200both absolute and relative imports, 0 is absolute, a positive number\n\
201is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000202
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000203
Guido van Rossum79f25d91997-04-29 20:08:16 +0000204static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000205builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000206{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000207 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000208}
209
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000210PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000211"abs(number) -> number\n\
212\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000213Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000214
Raymond Hettinger96229b12005-03-11 06:49:40 +0000215static PyObject *
216builtin_all(PyObject *self, PyObject *v)
217{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000218 PyObject *it, *item;
219 PyObject *(*iternext)(PyObject *);
220 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000221
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000222 it = PyObject_GetIter(v);
223 if (it == NULL)
224 return NULL;
225 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000226
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000227 for (;;) {
228 item = iternext(it);
229 if (item == NULL)
230 break;
231 cmp = PyObject_IsTrue(item);
232 Py_DECREF(item);
233 if (cmp < 0) {
234 Py_DECREF(it);
235 return NULL;
236 }
237 if (cmp == 0) {
238 Py_DECREF(it);
239 Py_RETURN_FALSE;
240 }
241 }
242 Py_DECREF(it);
243 if (PyErr_Occurred()) {
244 if (PyErr_ExceptionMatches(PyExc_StopIteration))
245 PyErr_Clear();
246 else
247 return NULL;
248 }
249 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000250}
251
252PyDoc_STRVAR(all_doc,
253"all(iterable) -> bool\n\
254\n\
255Return True if bool(x) is True for all values x in the iterable.");
256
257static PyObject *
258builtin_any(PyObject *self, PyObject *v)
259{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000260 PyObject *it, *item;
261 PyObject *(*iternext)(PyObject *);
262 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000263
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000264 it = PyObject_GetIter(v);
265 if (it == NULL)
266 return NULL;
267 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000268
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000269 for (;;) {
270 item = iternext(it);
271 if (item == NULL)
272 break;
273 cmp = PyObject_IsTrue(item);
274 Py_DECREF(item);
275 if (cmp < 0) {
276 Py_DECREF(it);
277 return NULL;
278 }
279 if (cmp == 1) {
280 Py_DECREF(it);
281 Py_RETURN_TRUE;
282 }
283 }
284 Py_DECREF(it);
285 if (PyErr_Occurred()) {
286 if (PyErr_ExceptionMatches(PyExc_StopIteration))
287 PyErr_Clear();
288 else
289 return NULL;
290 }
291 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000292}
293
294PyDoc_STRVAR(any_doc,
295"any(iterable) -> bool\n\
296\n\
297Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000298
Georg Brandl559e5d72008-06-11 18:37:52 +0000299static PyObject *
300builtin_ascii(PyObject *self, PyObject *v)
301{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000302 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000303}
304
305PyDoc_STRVAR(ascii_doc,
306"ascii(object) -> string\n\
307\n\
308As repr(), return a string containing a printable representation of an\n\
309object, but escape the non-ASCII characters in the string returned by\n\
310repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
311to that returned by repr() in Python 2.");
312
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000313
Guido van Rossum79f25d91997-04-29 20:08:16 +0000314static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000315builtin_bin(PyObject *self, PyObject *v)
316{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000317 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000318}
319
320PyDoc_STRVAR(bin_doc,
321"bin(number) -> string\n\
322\n\
323Return the binary representation of an integer or long integer.");
324
325
Raymond Hettinger17301e92008-03-13 00:19:26 +0000326typedef struct {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000327 PyObject_HEAD
328 PyObject *func;
329 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000330} filterobject;
331
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000332static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000333filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000334{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000335 PyObject *func, *seq;
336 PyObject *it;
337 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000338
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000339 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
340 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000341
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000342 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
343 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000344
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000345 /* Get iterator. */
346 it = PyObject_GetIter(seq);
347 if (it == NULL)
348 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000349
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000350 /* create filterobject structure */
351 lz = (filterobject *)type->tp_alloc(type, 0);
352 if (lz == NULL) {
353 Py_DECREF(it);
354 return NULL;
355 }
356 Py_INCREF(func);
357 lz->func = func;
358 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000359
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000360 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000361}
362
363static void
364filter_dealloc(filterobject *lz)
365{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000366 PyObject_GC_UnTrack(lz);
367 Py_XDECREF(lz->func);
368 Py_XDECREF(lz->it);
369 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000370}
371
372static int
373filter_traverse(filterobject *lz, visitproc visit, void *arg)
374{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000375 Py_VISIT(lz->it);
376 Py_VISIT(lz->func);
377 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000378}
379
380static PyObject *
381filter_next(filterobject *lz)
382{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000383 PyObject *item;
384 PyObject *it = lz->it;
385 long ok;
386 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000387
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000388 iternext = *Py_TYPE(it)->tp_iternext;
389 for (;;) {
390 item = iternext(it);
391 if (item == NULL)
392 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000393
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000394 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
395 ok = PyObject_IsTrue(item);
396 } else {
397 PyObject *good;
398 good = PyObject_CallFunctionObjArgs(lz->func,
399 item, NULL);
400 if (good == NULL) {
401 Py_DECREF(item);
402 return NULL;
403 }
404 ok = PyObject_IsTrue(good);
405 Py_DECREF(good);
406 }
407 if (ok)
408 return item;
409 Py_DECREF(item);
410 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000411}
412
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000413PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000414"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000415\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000416Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000417is true. If function is None, return the items that are true.");
418
419PyTypeObject PyFilter_Type = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000420 PyVarObject_HEAD_INIT(&PyType_Type, 0)
421 "filter", /* tp_name */
422 sizeof(filterobject), /* tp_basicsize */
423 0, /* tp_itemsize */
424 /* methods */
425 (destructor)filter_dealloc, /* tp_dealloc */
426 0, /* tp_print */
427 0, /* tp_getattr */
428 0, /* tp_setattr */
429 0, /* tp_reserved */
430 0, /* tp_repr */
431 0, /* tp_as_number */
432 0, /* tp_as_sequence */
433 0, /* tp_as_mapping */
434 0, /* tp_hash */
435 0, /* tp_call */
436 0, /* tp_str */
437 PyObject_GenericGetAttr, /* tp_getattro */
438 0, /* tp_setattro */
439 0, /* tp_as_buffer */
440 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
441 Py_TPFLAGS_BASETYPE, /* tp_flags */
442 filter_doc, /* tp_doc */
443 (traverseproc)filter_traverse, /* tp_traverse */
444 0, /* tp_clear */
445 0, /* tp_richcompare */
446 0, /* tp_weaklistoffset */
447 PyObject_SelfIter, /* tp_iter */
448 (iternextfunc)filter_next, /* tp_iternext */
449 0, /* tp_methods */
450 0, /* tp_members */
451 0, /* tp_getset */
452 0, /* tp_base */
453 0, /* tp_dict */
454 0, /* tp_descr_get */
455 0, /* tp_descr_set */
456 0, /* tp_dictoffset */
457 0, /* tp_init */
458 PyType_GenericAlloc, /* tp_alloc */
459 filter_new, /* tp_new */
460 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000461};
462
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000463
Eric Smith8c663262007-08-25 02:26:07 +0000464static PyObject *
465builtin_format(PyObject *self, PyObject *args)
466{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000467 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000468 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000469
Eric Smith8fd3eba2008-02-17 19:48:00 +0000470 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000471 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000472
Eric Smith8fd3eba2008-02-17 19:48:00 +0000473 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000474}
475
Eric Smith8c663262007-08-25 02:26:07 +0000476PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000477"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000478\n\
Eric Smith81936692007-08-31 01:14:01 +0000479Returns value.__format__(format_spec)\n\
480format_spec defaults to \"\"");
481
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000482static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000483builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000484{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000485 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000486
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000487 if (!PyArg_ParseTuple(args, "i:chr", &x))
488 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000489
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000490 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000491}
492
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000493PyDoc_VAR(chr_doc) = PyDoc_STR(
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000494"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000495\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000496Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000497)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000498#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000499PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000500"\nIf 0x10000 <= i, a surrogate pair is returned."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000501)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000502#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000503;
Guido van Rossum09095f32000-03-10 23:00:52 +0000504
505
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000506static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000507source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000508{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000509 char *str;
510 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000511
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000512 if (PyUnicode_Check(cmd)) {
513 cf->cf_flags |= PyCF_IGNORE_COOKIE;
514 cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL);
515 if (cmd == NULL)
516 return NULL;
517 }
518 else if (!PyObject_CheckReadBuffer(cmd)) {
519 PyErr_Format(PyExc_TypeError,
520 "%s() arg 1 must be a %s object",
521 funcname, what);
522 return NULL;
523 }
524 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
525 return NULL;
526 }
527 if (strlen(str) != size) {
528 PyErr_SetString(PyExc_TypeError,
529 "source code string cannot contain null bytes");
530 return NULL;
531 }
532 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000533}
534
Guido van Rossum79f25d91997-04-29 20:08:16 +0000535static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000536builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000537{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000538 char *str;
Victor Stinner15244f72010-10-19 01:22:07 +0000539 PyObject *filename_obj;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000540 char *filename;
541 char *startstr;
542 int mode = -1;
543 int dont_inherit = 0;
544 int supplied_flags = 0;
545 int is_ast;
546 PyCompilerFlags cf;
547 PyObject *cmd;
548 static char *kwlist[] = {"source", "filename", "mode", "flags",
549 "dont_inherit", NULL};
550 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner15244f72010-10-19 01:22:07 +0000551 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000552
Victor Stinner15244f72010-10-19 01:22:07 +0000553 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|ii:compile", kwlist,
554 &cmd,
555 PyUnicode_FSConverter, &filename_obj,
556 &startstr, &supplied_flags,
557 &dont_inherit))
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000558 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000559
Victor Stinner15244f72010-10-19 01:22:07 +0000560 filename = PyBytes_AS_STRING(filename_obj);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000561 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000562
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000563 if (supplied_flags &
564 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
565 {
566 PyErr_SetString(PyExc_ValueError,
567 "compile(): unrecognised flags");
Victor Stinner15244f72010-10-19 01:22:07 +0000568 goto error;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000569 }
570 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000571
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000572 if (!dont_inherit) {
573 PyEval_MergeCompilerFlags(&cf);
574 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000575
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000576 if (strcmp(startstr, "exec") == 0)
577 mode = 0;
578 else if (strcmp(startstr, "eval") == 0)
579 mode = 1;
580 else if (strcmp(startstr, "single") == 0)
581 mode = 2;
582 else {
583 PyErr_SetString(PyExc_ValueError,
584 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner15244f72010-10-19 01:22:07 +0000585 goto error;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000586 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000587
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000588 is_ast = PyAST_Check(cmd);
589 if (is_ast == -1)
Victor Stinner15244f72010-10-19 01:22:07 +0000590 goto error;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000591 if (is_ast) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000592 if (supplied_flags & PyCF_ONLY_AST) {
593 Py_INCREF(cmd);
594 result = cmd;
595 }
596 else {
597 PyArena *arena;
598 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000599
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000600 arena = PyArena_New();
601 mod = PyAST_obj2mod(cmd, arena, mode);
602 if (mod == NULL) {
603 PyArena_Free(arena);
Victor Stinner15244f72010-10-19 01:22:07 +0000604 goto error;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000605 }
606 result = (PyObject*)PyAST_Compile(mod, filename,
607 &cf, arena);
608 PyArena_Free(arena);
609 }
Victor Stinner15244f72010-10-19 01:22:07 +0000610 goto finally;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000611 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000612
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000613 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
614 if (str == NULL)
Victor Stinner15244f72010-10-19 01:22:07 +0000615 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000616
Victor Stinner15244f72010-10-19 01:22:07 +0000617 result = Py_CompileStringFlags(str, filename, start[mode], &cf);
618 goto finally;
619
620error:
621 result = NULL;
622finally:
623 Py_DECREF(filename_obj);
624 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000625}
626
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000627PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000628"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000629\n\
630Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000631into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000632The filename will be used for run-time error messages.\n\
633The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000634single (interactive) statement, or 'eval' to compile an expression.\n\
635The flags argument, if present, controls which future statements influence\n\
636the compilation of the code.\n\
637The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
638the effects of any future statements in effect in the code calling\n\
639compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000640in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000641
Guido van Rossum79f25d91997-04-29 20:08:16 +0000642static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000643builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000644{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000645 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000646
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000647 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
648 return NULL;
649 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000650}
651
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000652PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000653"dir([object]) -> list of strings\n"
654"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000655"If called without an argument, return the names in the current scope.\n"
656"Else, return an alphabetized list of names comprising (some of) the attributes\n"
657"of the given object, and of attributes reachable from it.\n"
658"If the object supplies a method named __dir__, it will be used; otherwise\n"
659"the default dir() logic is used and returns:\n"
660" for a module object: the module's attributes.\n"
661" for a class object: its attributes, and recursively the attributes\n"
662" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000663" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000664" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000665
Guido van Rossum79f25d91997-04-29 20:08:16 +0000666static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000667builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000668{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000669 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000670
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000671 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
672 return NULL;
673 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000674}
675
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000676PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000677"divmod(x, y) -> (div, mod)\n\
678\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000679Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000680
681
Guido van Rossum79f25d91997-04-29 20:08:16 +0000682static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000683builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000684{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000685 PyObject *cmd, *result, *tmp = NULL;
686 PyObject *globals = Py_None, *locals = Py_None;
687 char *str;
688 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000689
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000690 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
691 return NULL;
692 if (locals != Py_None && !PyMapping_Check(locals)) {
693 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
694 return NULL;
695 }
696 if (globals != Py_None && !PyDict_Check(globals)) {
697 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
698 "globals must be a real dict; try eval(expr, {}, mapping)"
699 : "globals must be a dict");
700 return NULL;
701 }
702 if (globals == Py_None) {
703 globals = PyEval_GetGlobals();
704 if (locals == Py_None)
705 locals = PyEval_GetLocals();
706 }
707 else if (locals == Py_None)
708 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000709
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000710 if (globals == NULL || locals == NULL) {
711 PyErr_SetString(PyExc_TypeError,
712 "eval must be given globals and locals "
713 "when called without a frame");
714 return NULL;
715 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000716
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000717 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
718 if (PyDict_SetItemString(globals, "__builtins__",
719 PyEval_GetBuiltins()) != 0)
720 return NULL;
721 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000722
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000723 if (PyCode_Check(cmd)) {
724 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
725 PyErr_SetString(PyExc_TypeError,
726 "code object passed to eval() may not contain free variables");
727 return NULL;
728 }
729 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
730 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000731
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000732 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
733 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
734 if (str == NULL)
735 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000736
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000737 while (*str == ' ' || *str == '\t')
738 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000739
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000740 (void)PyEval_MergeCompilerFlags(&cf);
741 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
742 Py_XDECREF(tmp);
743 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000744}
745
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000746PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000747"eval(source[, globals[, locals]]) -> value\n\
748\n\
749Evaluate the source in the context of globals and locals.\n\
750The source may be a string representing a Python expression\n\
751or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000752The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000753defaulting to the current globals and locals.\n\
754If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000755
Georg Brandl7cae87c2006-09-06 06:51:57 +0000756static PyObject *
757builtin_exec(PyObject *self, PyObject *args)
758{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000759 PyObject *v;
760 PyObject *prog, *globals = Py_None, *locals = Py_None;
761 int plain = 0;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000762
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000763 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
764 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000765
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000766 if (globals == Py_None) {
767 globals = PyEval_GetGlobals();
768 if (locals == Py_None) {
769 locals = PyEval_GetLocals();
770 plain = 1;
771 }
772 if (!globals || !locals) {
773 PyErr_SetString(PyExc_SystemError,
774 "globals and locals cannot be NULL");
775 return NULL;
776 }
777 }
778 else if (locals == Py_None)
779 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000780
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000781 if (!PyDict_Check(globals)) {
782 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
783 globals->ob_type->tp_name);
784 return NULL;
785 }
786 if (!PyMapping_Check(locals)) {
787 PyErr_Format(PyExc_TypeError,
788 "arg 3 must be a mapping or None, not %.100s",
789 locals->ob_type->tp_name);
790 return NULL;
791 }
792 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
793 if (PyDict_SetItemString(globals, "__builtins__",
794 PyEval_GetBuiltins()) != 0)
795 return NULL;
796 }
797
798 if (PyCode_Check(prog)) {
799 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
800 PyErr_SetString(PyExc_TypeError,
801 "code object passed to exec() may not "
802 "contain free variables");
803 return NULL;
804 }
805 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
806 }
807 else {
808 char *str;
809 PyCompilerFlags cf;
810 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
811 str = source_as_string(prog, "exec",
812 "string, bytes or code", &cf);
813 if (str == NULL)
814 return NULL;
815 if (PyEval_MergeCompilerFlags(&cf))
816 v = PyRun_StringFlags(str, Py_file_input, globals,
817 locals, &cf);
818 else
819 v = PyRun_String(str, Py_file_input, globals, locals);
820 }
821 if (v == NULL)
822 return NULL;
823 Py_DECREF(v);
824 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000825}
826
827PyDoc_STRVAR(exec_doc,
828"exec(object[, globals[, locals]])\n\
829\n\
Mark Dickinson188aace2009-12-19 21:20:55 +0000830Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000831object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000832The globals and locals are dictionaries, defaulting to the current\n\
833globals and locals. If only globals is given, locals defaults to it.");
834
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000835
Guido van Rossum79f25d91997-04-29 20:08:16 +0000836static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000837builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000838{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000839 PyObject *v, *result, *dflt = NULL;
840 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000841
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000842 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
843 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000844
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000845 if (!PyUnicode_Check(name)) {
846 PyErr_SetString(PyExc_TypeError,
847 "getattr(): attribute name must be string");
848 return NULL;
849 }
850 result = PyObject_GetAttr(v, name);
851 if (result == NULL && dflt != NULL &&
852 PyErr_ExceptionMatches(PyExc_AttributeError))
853 {
854 PyErr_Clear();
855 Py_INCREF(dflt);
856 result = dflt;
857 }
858 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000859}
860
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000861PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000862"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000863\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000864Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
865When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000866exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000867
868
Guido van Rossum79f25d91997-04-29 20:08:16 +0000869static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000870builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000871{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000872 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000873
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000874 d = PyEval_GetGlobals();
875 Py_XINCREF(d);
876 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000877}
878
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000879PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000880"globals() -> dictionary\n\
881\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000882Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000883
884
Guido van Rossum79f25d91997-04-29 20:08:16 +0000885static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000886builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000887{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000888 PyObject *v;
889 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000890
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000891 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
892 return NULL;
893 if (!PyUnicode_Check(name)) {
894 PyErr_SetString(PyExc_TypeError,
895 "hasattr(): attribute name must be string");
896 return NULL;
897 }
898 v = PyObject_GetAttr(v, name);
899 if (v == NULL) {
900 if (!PyErr_ExceptionMatches(PyExc_Exception))
901 return NULL;
902 else {
903 PyErr_Clear();
904 Py_INCREF(Py_False);
905 return Py_False;
906 }
907 }
908 Py_DECREF(v);
909 Py_INCREF(Py_True);
910 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000911}
912
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000913PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000914"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000915\n\
916Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000917(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000918
919
Guido van Rossum79f25d91997-04-29 20:08:16 +0000920static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000921builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000922{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000923 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000924}
925
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000926PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000927"id(object) -> integer\n\
928\n\
929Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000930simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000931
932
Raymond Hettingera6c60372008-03-13 01:26:19 +0000933/* map object ************************************************************/
934
935typedef struct {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000936 PyObject_HEAD
937 PyObject *iters;
938 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000939} mapobject;
940
Guido van Rossum79f25d91997-04-29 20:08:16 +0000941static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000942map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000943{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000944 PyObject *it, *iters, *func;
945 mapobject *lz;
946 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000947
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000948 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
949 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000950
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000951 numargs = PyTuple_Size(args);
952 if (numargs < 2) {
953 PyErr_SetString(PyExc_TypeError,
954 "map() must have at least two arguments.");
955 return NULL;
956 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000957
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000958 iters = PyTuple_New(numargs-1);
959 if (iters == NULL)
960 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000961
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000962 for (i=1 ; i<numargs ; i++) {
963 /* Get iterator. */
964 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
965 if (it == NULL) {
966 Py_DECREF(iters);
967 return NULL;
968 }
969 PyTuple_SET_ITEM(iters, i-1, it);
970 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000971
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000972 /* create mapobject structure */
973 lz = (mapobject *)type->tp_alloc(type, 0);
974 if (lz == NULL) {
975 Py_DECREF(iters);
976 return NULL;
977 }
978 lz->iters = iters;
979 func = PyTuple_GET_ITEM(args, 0);
980 Py_INCREF(func);
981 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000982
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000983 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000984}
985
986static void
987map_dealloc(mapobject *lz)
988{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000989 PyObject_GC_UnTrack(lz);
990 Py_XDECREF(lz->iters);
991 Py_XDECREF(lz->func);
992 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +0000993}
994
995static int
996map_traverse(mapobject *lz, visitproc visit, void *arg)
997{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000998 Py_VISIT(lz->iters);
999 Py_VISIT(lz->func);
1000 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001001}
1002
1003static PyObject *
1004map_next(mapobject *lz)
1005{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001006 PyObject *val;
1007 PyObject *argtuple;
1008 PyObject *result;
1009 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001010
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001011 numargs = PyTuple_Size(lz->iters);
1012 argtuple = PyTuple_New(numargs);
1013 if (argtuple == NULL)
1014 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001015
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001016 for (i=0 ; i<numargs ; i++) {
1017 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1018 if (val == NULL) {
1019 Py_DECREF(argtuple);
1020 return NULL;
1021 }
1022 PyTuple_SET_ITEM(argtuple, i, val);
1023 }
1024 result = PyObject_Call(lz->func, argtuple, NULL);
1025 Py_DECREF(argtuple);
1026 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001027}
1028
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001029PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001030"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001031\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001032Make an iterator that computes the function using arguments from\n\
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001033each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001034
Raymond Hettingera6c60372008-03-13 01:26:19 +00001035PyTypeObject PyMap_Type = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001036 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1037 "map", /* tp_name */
1038 sizeof(mapobject), /* tp_basicsize */
1039 0, /* tp_itemsize */
1040 /* methods */
1041 (destructor)map_dealloc, /* tp_dealloc */
1042 0, /* tp_print */
1043 0, /* tp_getattr */
1044 0, /* tp_setattr */
1045 0, /* tp_reserved */
1046 0, /* tp_repr */
1047 0, /* tp_as_number */
1048 0, /* tp_as_sequence */
1049 0, /* tp_as_mapping */
1050 0, /* tp_hash */
1051 0, /* tp_call */
1052 0, /* tp_str */
1053 PyObject_GenericGetAttr, /* tp_getattro */
1054 0, /* tp_setattro */
1055 0, /* tp_as_buffer */
1056 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1057 Py_TPFLAGS_BASETYPE, /* tp_flags */
1058 map_doc, /* tp_doc */
1059 (traverseproc)map_traverse, /* tp_traverse */
1060 0, /* tp_clear */
1061 0, /* tp_richcompare */
1062 0, /* tp_weaklistoffset */
1063 PyObject_SelfIter, /* tp_iter */
1064 (iternextfunc)map_next, /* tp_iternext */
1065 0, /* tp_methods */
1066 0, /* tp_members */
1067 0, /* tp_getset */
1068 0, /* tp_base */
1069 0, /* tp_dict */
1070 0, /* tp_descr_get */
1071 0, /* tp_descr_set */
1072 0, /* tp_dictoffset */
1073 0, /* tp_init */
1074 PyType_GenericAlloc, /* tp_alloc */
1075 map_new, /* tp_new */
1076 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001077};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001078
Guido van Rossum79f25d91997-04-29 20:08:16 +00001079static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001080builtin_next(PyObject *self, PyObject *args)
1081{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001082 PyObject *it, *res;
1083 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001084
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001085 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1086 return NULL;
1087 if (!PyIter_Check(it)) {
1088 PyErr_Format(PyExc_TypeError,
1089 "%.200s object is not an iterator",
1090 it->ob_type->tp_name);
1091 return NULL;
1092 }
1093
1094 res = (*it->ob_type->tp_iternext)(it);
1095 if (res != NULL) {
1096 return res;
1097 } else if (def != NULL) {
1098 if (PyErr_Occurred()) {
1099 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1100 return NULL;
1101 PyErr_Clear();
1102 }
1103 Py_INCREF(def);
1104 return def;
1105 } else if (PyErr_Occurred()) {
1106 return NULL;
1107 } else {
1108 PyErr_SetNone(PyExc_StopIteration);
1109 return NULL;
1110 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001111}
1112
1113PyDoc_STRVAR(next_doc,
1114"next(iterator[, default])\n\
1115\n\
1116Return the next item from the iterator. If default is given and the iterator\n\
1117is exhausted, it is returned instead of raising StopIteration.");
1118
1119
1120static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001121builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001122{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001123 PyObject *v;
1124 PyObject *name;
1125 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001126
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001127 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1128 return NULL;
1129 if (PyObject_SetAttr(v, name, value) != 0)
1130 return NULL;
1131 Py_INCREF(Py_None);
1132 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001133}
1134
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001135PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001136"setattr(object, name, value)\n\
1137\n\
1138Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001139``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001140
1141
Guido van Rossum79f25d91997-04-29 20:08:16 +00001142static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001143builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001144{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001145 PyObject *v;
1146 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001147
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001148 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1149 return NULL;
1150 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1151 return NULL;
1152 Py_INCREF(Py_None);
1153 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001154}
1155
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001156PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001157"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001158\n\
1159Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001160``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001161
1162
Guido van Rossum79f25d91997-04-29 20:08:16 +00001163static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001164builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001165{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001166 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001167
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001168 x = PyObject_Hash(v);
1169 if (x == -1)
1170 return NULL;
1171 return PyLong_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001172}
1173
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001174PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001175"hash(object) -> integer\n\
1176\n\
1177Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001178the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001179
1180
Guido van Rossum79f25d91997-04-29 20:08:16 +00001181static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001182builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001183{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001184 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001185}
1186
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001187PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001188"hex(number) -> string\n\
1189\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001190Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001191
1192
Guido van Rossum79f25d91997-04-29 20:08:16 +00001193static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001194builtin_iter(PyObject *self, PyObject *args)
1195{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001196 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001197
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001198 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1199 return NULL;
1200 if (w == NULL)
1201 return PyObject_GetIter(v);
1202 if (!PyCallable_Check(v)) {
1203 PyErr_SetString(PyExc_TypeError,
1204 "iter(v, w): v must be callable");
1205 return NULL;
1206 }
1207 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001208}
1209
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001210PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001211"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001212iter(callable, sentinel) -> iterator\n\
1213\n\
1214Get an iterator from an object. In the first form, the argument must\n\
1215supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001216In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001217
1218
1219static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001220builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001221{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001222 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001223
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001224 res = PyObject_Size(v);
1225 if (res < 0 && PyErr_Occurred())
1226 return NULL;
1227 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001228}
1229
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001230PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001231"len(object) -> integer\n\
1232\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001233Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001234
1235
Guido van Rossum79f25d91997-04-29 20:08:16 +00001236static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001237builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001238{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001239 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001240
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001241 d = PyEval_GetLocals();
1242 Py_XINCREF(d);
1243 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001244}
1245
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001246PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001247"locals() -> dictionary\n\
1248\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001249Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001250
1251
Guido van Rossum79f25d91997-04-29 20:08:16 +00001252static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001253min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001254{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001255 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1256 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001257
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001258 if (PyTuple_Size(args) > 1)
1259 v = args;
1260 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1261 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001262
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001263 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1264 keyfunc = PyDict_GetItemString(kwds, "key");
1265 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1266 PyErr_Format(PyExc_TypeError,
1267 "%s() got an unexpected keyword argument", name);
1268 return NULL;
1269 }
1270 Py_INCREF(keyfunc);
1271 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001272
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001273 it = PyObject_GetIter(v);
1274 if (it == NULL) {
1275 Py_XDECREF(keyfunc);
1276 return NULL;
1277 }
Tim Petersc3074532001-05-03 07:00:32 +00001278
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001279 maxitem = NULL; /* the result */
1280 maxval = NULL; /* the value associated with the result */
1281 while (( item = PyIter_Next(it) )) {
1282 /* get the value from the key function */
1283 if (keyfunc != NULL) {
1284 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1285 if (val == NULL)
1286 goto Fail_it_item;
1287 }
1288 /* no key function; the value is the item */
1289 else {
1290 val = item;
1291 Py_INCREF(val);
1292 }
Tim Petersc3074532001-05-03 07:00:32 +00001293
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001294 /* maximum value and item are unset; set them */
1295 if (maxval == NULL) {
1296 maxitem = item;
1297 maxval = val;
1298 }
1299 /* maximum value and item are set; update them as necessary */
1300 else {
1301 int cmp = PyObject_RichCompareBool(val, maxval, op);
1302 if (cmp < 0)
1303 goto Fail_it_item_and_val;
1304 else if (cmp > 0) {
1305 Py_DECREF(maxval);
1306 Py_DECREF(maxitem);
1307 maxval = val;
1308 maxitem = item;
1309 }
1310 else {
1311 Py_DECREF(item);
1312 Py_DECREF(val);
1313 }
1314 }
1315 }
1316 if (PyErr_Occurred())
1317 goto Fail_it;
1318 if (maxval == NULL) {
1319 PyErr_Format(PyExc_ValueError,
1320 "%s() arg is an empty sequence", name);
1321 assert(maxitem == NULL);
1322 }
1323 else
1324 Py_DECREF(maxval);
1325 Py_DECREF(it);
1326 Py_XDECREF(keyfunc);
1327 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001328
1329Fail_it_item_and_val:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001330 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001331Fail_it_item:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001332 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001333Fail_it:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001334 Py_XDECREF(maxval);
1335 Py_XDECREF(maxitem);
1336 Py_DECREF(it);
1337 Py_XDECREF(keyfunc);
1338 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001339}
1340
Guido van Rossum79f25d91997-04-29 20:08:16 +00001341static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001342builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001343{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001344 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001345}
1346
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001347PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001348"min(iterable[, key=func]) -> value\n\
1349min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001350\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001351With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001352With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001353
1354
Guido van Rossum79f25d91997-04-29 20:08:16 +00001355static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001356builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001357{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001358 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001359}
1360
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001361PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001362"max(iterable[, key=func]) -> value\n\
1363max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001364\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001365With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001366With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001367
1368
Guido van Rossum79f25d91997-04-29 20:08:16 +00001369static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001370builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001371{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001372 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001373}
1374
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001375PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001376"oct(number) -> string\n\
1377\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001378Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001379
1380
Guido van Rossum79f25d91997-04-29 20:08:16 +00001381static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001382builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001383{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001384 long ord;
1385 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001386
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001387 if (PyBytes_Check(obj)) {
1388 size = PyBytes_GET_SIZE(obj);
1389 if (size == 1) {
1390 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1391 return PyLong_FromLong(ord);
1392 }
1393 }
1394 else if (PyUnicode_Check(obj)) {
1395 size = PyUnicode_GET_SIZE(obj);
1396 if (size == 1) {
1397 ord = (long)*PyUnicode_AS_UNICODE(obj);
1398 return PyLong_FromLong(ord);
1399 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001400#ifndef Py_UNICODE_WIDE
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001401 if (size == 2) {
1402 /* Decode a valid surrogate pair */
1403 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1404 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1405 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1406 0xDC00 <= c1 && c1 <= 0xDFFF) {
1407 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1408 0x00010000);
1409 return PyLong_FromLong(ord);
1410 }
1411 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001412#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001413 }
1414 else if (PyByteArray_Check(obj)) {
1415 /* XXX Hopefully this is temporary */
1416 size = PyByteArray_GET_SIZE(obj);
1417 if (size == 1) {
1418 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1419 return PyLong_FromLong(ord);
1420 }
1421 }
1422 else {
1423 PyErr_Format(PyExc_TypeError,
1424 "ord() expected string of length 1, but " \
1425 "%.200s found", obj->ob_type->tp_name);
1426 return NULL;
1427 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001428
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001429 PyErr_Format(PyExc_TypeError,
1430 "ord() expected a character, "
1431 "but string of length %zd found",
1432 size);
1433 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001434}
1435
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001436PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001437"ord(c) -> integer\n\
1438\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001439Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001440)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001441#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001442PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001443"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001444)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001445#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001446;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001447
1448
Guido van Rossum79f25d91997-04-29 20:08:16 +00001449static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001450builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001451{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001452 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001453
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001454 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1455 return NULL;
1456 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001457}
1458
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001459PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001460"pow(x, y[, z]) -> number\n\
1461\n\
1462With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001463equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001464
1465
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001466
Guido van Rossum34343512006-11-30 22:13:52 +00001467static PyObject *
1468builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1469{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001470 static char *kwlist[] = {"sep", "end", "file", 0};
1471 static PyObject *dummy_args;
1472 PyObject *sep = NULL, *end = NULL, *file = NULL;
1473 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001474
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001475 if (dummy_args == NULL) {
1476 if (!(dummy_args = PyTuple_New(0)))
1477 return NULL;
1478 }
1479 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1480 kwlist, &sep, &end, &file))
1481 return NULL;
1482 if (file == NULL || file == Py_None) {
1483 file = PySys_GetObject("stdout");
1484 /* sys.stdout may be None when FILE* stdout isn't connected */
1485 if (file == Py_None)
1486 Py_RETURN_NONE;
1487 }
Guido van Rossum34343512006-11-30 22:13:52 +00001488
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001489 if (sep && sep != Py_None && !PyUnicode_Check(sep)) {
1490 PyErr_Format(PyExc_TypeError,
1491 "sep must be None or a string, not %.200s",
1492 sep->ob_type->tp_name);
1493 return NULL;
1494 }
1495 if (end && end != Py_None && !PyUnicode_Check(end)) {
1496 PyErr_Format(PyExc_TypeError,
1497 "end must be None or a string, not %.200s",
1498 end->ob_type->tp_name);
1499 return NULL;
1500 }
Guido van Rossum34343512006-11-30 22:13:52 +00001501
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001502 for (i = 0; i < PyTuple_Size(args); i++) {
1503 if (i > 0) {
1504 if (sep == NULL || sep == Py_None)
1505 err = PyFile_WriteString(" ", file);
1506 else
1507 err = PyFile_WriteObject(sep, file,
1508 Py_PRINT_RAW);
1509 if (err)
1510 return NULL;
1511 }
1512 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1513 Py_PRINT_RAW);
1514 if (err)
1515 return NULL;
1516 }
Guido van Rossum34343512006-11-30 22:13:52 +00001517
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001518 if (end == NULL || end == Py_None)
1519 err = PyFile_WriteString("\n", file);
1520 else
1521 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1522 if (err)
1523 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001524
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001525 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001526}
1527
1528PyDoc_STRVAR(print_doc,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001529"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001530\n\
1531Prints the values to a stream, or to sys.stdout by default.\n\
1532Optional keyword arguments:\n\
1533file: a file-like object (stream); defaults to the current sys.stdout.\n\
1534sep: string inserted between values, default a space.\n\
1535end: string appended after the last value, default a newline.");
1536
1537
Guido van Rossuma88a0332007-02-26 16:59:55 +00001538static PyObject *
1539builtin_input(PyObject *self, PyObject *args)
1540{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001541 PyObject *promptarg = NULL;
1542 PyObject *fin = PySys_GetObject("stdin");
1543 PyObject *fout = PySys_GetObject("stdout");
1544 PyObject *ferr = PySys_GetObject("stderr");
1545 PyObject *tmp;
1546 long fd;
1547 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001548
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001549 /* Parse arguments */
1550 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1551 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001552
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001553 /* Check that stdin/out/err are intact */
1554 if (fin == NULL || fin == Py_None) {
1555 PyErr_SetString(PyExc_RuntimeError,
1556 "input(): lost sys.stdin");
1557 return NULL;
1558 }
1559 if (fout == NULL || fout == Py_None) {
1560 PyErr_SetString(PyExc_RuntimeError,
1561 "input(): lost sys.stdout");
1562 return NULL;
1563 }
1564 if (ferr == NULL || ferr == Py_None) {
1565 PyErr_SetString(PyExc_RuntimeError,
1566 "input(): lost sys.stderr");
1567 return NULL;
1568 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001569
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001570 /* First of all, flush stderr */
1571 tmp = PyObject_CallMethod(ferr, "flush", "");
1572 if (tmp == NULL)
1573 PyErr_Clear();
1574 else
1575 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001576
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001577 /* We should only use (GNU) readline if Python's sys.stdin and
1578 sys.stdout are the same as C's stdin and stdout, because we
1579 need to pass it those. */
1580 tmp = PyObject_CallMethod(fin, "fileno", "");
1581 if (tmp == NULL) {
1582 PyErr_Clear();
1583 tty = 0;
1584 }
1585 else {
1586 fd = PyLong_AsLong(tmp);
1587 Py_DECREF(tmp);
1588 if (fd < 0 && PyErr_Occurred())
1589 return NULL;
1590 tty = fd == fileno(stdin) && isatty(fd);
1591 }
1592 if (tty) {
1593 tmp = PyObject_CallMethod(fout, "fileno", "");
1594 if (tmp == NULL)
1595 PyErr_Clear();
1596 else {
1597 fd = PyLong_AsLong(tmp);
1598 Py_DECREF(tmp);
1599 if (fd < 0 && PyErr_Occurred())
1600 return NULL;
1601 tty = fd == fileno(stdout) && isatty(fd);
1602 }
1603 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001604
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001605 /* If we're interactive, use (GNU) readline */
1606 if (tty) {
1607 PyObject *po;
1608 char *prompt;
1609 char *s;
1610 PyObject *stdin_encoding;
1611 PyObject *result;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001612
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001613 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1614 if (!stdin_encoding)
1615 /* stdin is a text stream, so it must have an
1616 encoding. */
1617 return NULL;
1618 tmp = PyObject_CallMethod(fout, "flush", "");
1619 if (tmp == NULL)
1620 PyErr_Clear();
1621 else
1622 Py_DECREF(tmp);
1623 if (promptarg != NULL) {
1624 PyObject *stringpo;
1625 PyObject *stdout_encoding;
1626 stdout_encoding = PyObject_GetAttrString(fout,
1627 "encoding");
1628 if (stdout_encoding == NULL) {
1629 Py_DECREF(stdin_encoding);
1630 return NULL;
1631 }
1632 stringpo = PyObject_Str(promptarg);
1633 if (stringpo == NULL) {
1634 Py_DECREF(stdin_encoding);
1635 Py_DECREF(stdout_encoding);
1636 return NULL;
1637 }
1638 po = PyUnicode_AsEncodedString(stringpo,
1639 _PyUnicode_AsString(stdout_encoding), NULL);
1640 Py_DECREF(stdout_encoding);
1641 Py_DECREF(stringpo);
1642 if (po == NULL) {
1643 Py_DECREF(stdin_encoding);
1644 return NULL;
1645 }
1646 prompt = PyBytes_AsString(po);
1647 if (prompt == NULL) {
1648 Py_DECREF(stdin_encoding);
1649 Py_DECREF(po);
1650 return NULL;
1651 }
1652 }
1653 else {
1654 po = NULL;
1655 prompt = "";
1656 }
1657 s = PyOS_Readline(stdin, stdout, prompt);
1658 Py_XDECREF(po);
1659 if (s == NULL) {
1660 if (!PyErr_Occurred())
1661 PyErr_SetNone(PyExc_KeyboardInterrupt);
1662 Py_DECREF(stdin_encoding);
1663 return NULL;
1664 }
1665 if (*s == '\0') {
1666 PyErr_SetNone(PyExc_EOFError);
1667 result = NULL;
1668 }
1669 else { /* strip trailing '\n' */
1670 size_t len = strlen(s);
1671 if (len > PY_SSIZE_T_MAX) {
1672 PyErr_SetString(PyExc_OverflowError,
1673 "input: input too long");
1674 result = NULL;
1675 }
1676 else {
1677 result = PyUnicode_Decode
1678 (s, len-1,
1679 _PyUnicode_AsString(stdin_encoding),
1680 NULL);
1681 }
1682 }
1683 Py_DECREF(stdin_encoding);
1684 PyMem_FREE(s);
1685 return result;
1686 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001687
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001688 /* Fallback if we're not interactive */
1689 if (promptarg != NULL) {
1690 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1691 return NULL;
1692 }
1693 tmp = PyObject_CallMethod(fout, "flush", "");
1694 if (tmp == NULL)
1695 PyErr_Clear();
1696 else
1697 Py_DECREF(tmp);
1698 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001699}
1700
1701PyDoc_STRVAR(input_doc,
1702"input([prompt]) -> string\n\
1703\n\
1704Read a string from standard input. The trailing newline is stripped.\n\
1705If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1706On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1707is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001708
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001709
Guido van Rossum79f25d91997-04-29 20:08:16 +00001710static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001711builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001712{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001713 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001714}
1715
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001716PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001717"repr(object) -> string\n\
1718\n\
1719Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001720For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001721
1722
Guido van Rossum79f25d91997-04-29 20:08:16 +00001723static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001724builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001725{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001726 static PyObject *round_str = NULL;
1727 PyObject *ndigits = NULL;
1728 static char *kwlist[] = {"number", "ndigits", 0};
1729 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001730
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001731 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1732 kwlist, &number, &ndigits))
1733 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001734
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001735 if (Py_TYPE(number)->tp_dict == NULL) {
1736 if (PyType_Ready(Py_TYPE(number)) < 0)
1737 return NULL;
1738 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001739
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001740 if (round_str == NULL) {
1741 round_str = PyUnicode_InternFromString("__round__");
1742 if (round_str == NULL)
1743 return NULL;
1744 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001745
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001746 round = _PyType_Lookup(Py_TYPE(number), round_str);
1747 if (round == NULL) {
1748 PyErr_Format(PyExc_TypeError,
1749 "type %.100s doesn't define __round__ method",
1750 Py_TYPE(number)->tp_name);
1751 return NULL;
1752 }
Alex Martelliae211f92007-08-22 23:21:33 +00001753
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001754 if (ndigits == NULL)
1755 return PyObject_CallFunction(round, "O", number);
1756 else
1757 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001758}
1759
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001760PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001761"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001762\n\
1763Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001764This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001765same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001766
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001767
Raymond Hettinger64958a12003-12-17 20:43:33 +00001768static PyObject *
1769builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1770{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001771 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1772 PyObject *callable;
1773 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1774 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001775
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001776 /* args 1-3 should match listsort in Objects/listobject.c */
1777 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1778 kwlist, &seq, &keyfunc, &reverse))
1779 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001780
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001781 newlist = PySequence_List(seq);
1782 if (newlist == NULL)
1783 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001784
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001785 callable = PyObject_GetAttrString(newlist, "sort");
1786 if (callable == NULL) {
1787 Py_DECREF(newlist);
1788 return NULL;
1789 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001790
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001791 newargs = PyTuple_GetSlice(args, 1, 4);
1792 if (newargs == NULL) {
1793 Py_DECREF(newlist);
1794 Py_DECREF(callable);
1795 return NULL;
1796 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001797
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001798 v = PyObject_Call(callable, newargs, kwds);
1799 Py_DECREF(newargs);
1800 Py_DECREF(callable);
1801 if (v == NULL) {
1802 Py_DECREF(newlist);
1803 return NULL;
1804 }
1805 Py_DECREF(v);
1806 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001807}
1808
1809PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001810"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001811
Guido van Rossum79f25d91997-04-29 20:08:16 +00001812static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001813builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001814{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001815 PyObject *v = NULL;
1816 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001817
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001818 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1819 return NULL;
1820 if (v == NULL) {
1821 d = PyEval_GetLocals();
1822 if (d == NULL) {
1823 if (!PyErr_Occurred())
1824 PyErr_SetString(PyExc_SystemError,
1825 "vars(): no locals!?");
1826 }
1827 else
1828 Py_INCREF(d);
1829 }
1830 else {
1831 d = PyObject_GetAttrString(v, "__dict__");
1832 if (d == NULL) {
1833 PyErr_SetString(PyExc_TypeError,
1834 "vars() argument must have __dict__ attribute");
1835 return NULL;
1836 }
1837 }
1838 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001839}
1840
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001841PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001842"vars([object]) -> dictionary\n\
1843\n\
1844Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001845With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001846
Alex Martellia70b1912003-04-22 08:12:33 +00001847static PyObject*
1848builtin_sum(PyObject *self, PyObject *args)
1849{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001850 PyObject *seq;
1851 PyObject *result = NULL;
1852 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001853
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001854 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1855 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001856
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001857 iter = PyObject_GetIter(seq);
1858 if (iter == NULL)
1859 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001860
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001861 if (result == NULL) {
1862 result = PyLong_FromLong(0);
1863 if (result == NULL) {
1864 Py_DECREF(iter);
1865 return NULL;
1866 }
1867 } else {
1868 /* reject string values for 'start' parameter */
1869 if (PyUnicode_Check(result)) {
1870 PyErr_SetString(PyExc_TypeError,
1871 "sum() can't sum strings [use ''.join(seq) instead]");
1872 Py_DECREF(iter);
1873 return NULL;
1874 }
1875 if (PyByteArray_Check(result)) {
1876 PyErr_SetString(PyExc_TypeError,
1877 "sum() can't sum bytes [use b''.join(seq) instead]");
1878 Py_DECREF(iter);
1879 return NULL;
1880 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001881
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001882 Py_INCREF(result);
1883 }
Alex Martellia70b1912003-04-22 08:12:33 +00001884
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001885#ifndef SLOW_SUM
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001886 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1887 Assumes all inputs are the same type. If the assumption fails, default
1888 to the more general routine.
1889 */
1890 if (PyLong_CheckExact(result)) {
1891 int overflow;
1892 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1893 /* If this already overflowed, don't even enter the loop. */
1894 if (overflow == 0) {
1895 Py_DECREF(result);
1896 result = NULL;
1897 }
1898 while(result == NULL) {
1899 item = PyIter_Next(iter);
1900 if (item == NULL) {
1901 Py_DECREF(iter);
1902 if (PyErr_Occurred())
1903 return NULL;
1904 return PyLong_FromLong(i_result);
1905 }
1906 if (PyLong_CheckExact(item)) {
1907 long b = PyLong_AsLongAndOverflow(item, &overflow);
1908 long x = i_result + b;
1909 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1910 i_result = x;
1911 Py_DECREF(item);
1912 continue;
1913 }
1914 }
1915 /* Either overflowed or is not an int. Restore real objects and process normally */
1916 result = PyLong_FromLong(i_result);
1917 temp = PyNumber_Add(result, item);
1918 Py_DECREF(result);
1919 Py_DECREF(item);
1920 result = temp;
1921 if (result == NULL) {
1922 Py_DECREF(iter);
1923 return NULL;
1924 }
1925 }
1926 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001927
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001928 if (PyFloat_CheckExact(result)) {
1929 double f_result = PyFloat_AS_DOUBLE(result);
1930 Py_DECREF(result);
1931 result = NULL;
1932 while(result == NULL) {
1933 item = PyIter_Next(iter);
1934 if (item == NULL) {
1935 Py_DECREF(iter);
1936 if (PyErr_Occurred())
1937 return NULL;
1938 return PyFloat_FromDouble(f_result);
1939 }
1940 if (PyFloat_CheckExact(item)) {
1941 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1942 f_result += PyFloat_AS_DOUBLE(item);
1943 PyFPE_END_PROTECT(f_result)
1944 Py_DECREF(item);
1945 continue;
1946 }
1947 if (PyLong_CheckExact(item)) {
1948 long value;
1949 int overflow;
1950 value = PyLong_AsLongAndOverflow(item, &overflow);
1951 if (!overflow) {
1952 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1953 f_result += (double)value;
1954 PyFPE_END_PROTECT(f_result)
1955 Py_DECREF(item);
1956 continue;
1957 }
1958 }
1959 result = PyFloat_FromDouble(f_result);
1960 temp = PyNumber_Add(result, item);
1961 Py_DECREF(result);
1962 Py_DECREF(item);
1963 result = temp;
1964 if (result == NULL) {
1965 Py_DECREF(iter);
1966 return NULL;
1967 }
1968 }
1969 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001970#endif
1971
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001972 for(;;) {
1973 item = PyIter_Next(iter);
1974 if (item == NULL) {
1975 /* error, or end-of-sequence */
1976 if (PyErr_Occurred()) {
1977 Py_DECREF(result);
1978 result = NULL;
1979 }
1980 break;
1981 }
1982 temp = PyNumber_Add(result, item);
1983 Py_DECREF(result);
1984 Py_DECREF(item);
1985 result = temp;
1986 if (result == NULL)
1987 break;
1988 }
1989 Py_DECREF(iter);
1990 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00001991}
1992
1993PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001994"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00001995\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00001996Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
1997of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00001998empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00001999
2000
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002001static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002002builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002003{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002004 PyObject *inst;
2005 PyObject *cls;
2006 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002007
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002008 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2009 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002010
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002011 retval = PyObject_IsInstance(inst, cls);
2012 if (retval < 0)
2013 return NULL;
2014 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002015}
2016
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002017PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002018"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002019\n\
2020Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002021With a type as second argument, return whether that is the object's type.\n\
2022The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002023isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002024
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002025
2026static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002027builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002028{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002029 PyObject *derived;
2030 PyObject *cls;
2031 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002032
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002033 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2034 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002035
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002036 retval = PyObject_IsSubclass(derived, cls);
2037 if (retval < 0)
2038 return NULL;
2039 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002040}
2041
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002042PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002043"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002044\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002045Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2046When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2047is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002048
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002049
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002050typedef struct {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002051 PyObject_HEAD
2052 Py_ssize_t tuplesize;
2053 PyObject *ittuple; /* tuple of iterators */
2054 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002055} zipobject;
2056
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002057static PyObject *
2058zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002059{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002060 zipobject *lz;
2061 Py_ssize_t i;
2062 PyObject *ittuple; /* tuple of iterators */
2063 PyObject *result;
2064 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002065
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002066 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2067 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002068
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002069 /* args must be a tuple */
2070 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002071
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002072 /* obtain iterators */
2073 ittuple = PyTuple_New(tuplesize);
2074 if (ittuple == NULL)
2075 return NULL;
2076 for (i=0; i < tuplesize; ++i) {
2077 PyObject *item = PyTuple_GET_ITEM(args, i);
2078 PyObject *it = PyObject_GetIter(item);
2079 if (it == NULL) {
2080 if (PyErr_ExceptionMatches(PyExc_TypeError))
2081 PyErr_Format(PyExc_TypeError,
2082 "zip argument #%zd must support iteration",
2083 i+1);
2084 Py_DECREF(ittuple);
2085 return NULL;
2086 }
2087 PyTuple_SET_ITEM(ittuple, i, it);
2088 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002089
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002090 /* create a result holder */
2091 result = PyTuple_New(tuplesize);
2092 if (result == NULL) {
2093 Py_DECREF(ittuple);
2094 return NULL;
2095 }
2096 for (i=0 ; i < tuplesize ; i++) {
2097 Py_INCREF(Py_None);
2098 PyTuple_SET_ITEM(result, i, Py_None);
2099 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002100
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002101 /* create zipobject structure */
2102 lz = (zipobject *)type->tp_alloc(type, 0);
2103 if (lz == NULL) {
2104 Py_DECREF(ittuple);
2105 Py_DECREF(result);
2106 return NULL;
2107 }
2108 lz->ittuple = ittuple;
2109 lz->tuplesize = tuplesize;
2110 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002111
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002112 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002113}
2114
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002115static void
2116zip_dealloc(zipobject *lz)
2117{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002118 PyObject_GC_UnTrack(lz);
2119 Py_XDECREF(lz->ittuple);
2120 Py_XDECREF(lz->result);
2121 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002122}
2123
2124static int
2125zip_traverse(zipobject *lz, visitproc visit, void *arg)
2126{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002127 Py_VISIT(lz->ittuple);
2128 Py_VISIT(lz->result);
2129 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002130}
2131
2132static PyObject *
2133zip_next(zipobject *lz)
2134{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002135 Py_ssize_t i;
2136 Py_ssize_t tuplesize = lz->tuplesize;
2137 PyObject *result = lz->result;
2138 PyObject *it;
2139 PyObject *item;
2140 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002141
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002142 if (tuplesize == 0)
2143 return NULL;
2144 if (Py_REFCNT(result) == 1) {
2145 Py_INCREF(result);
2146 for (i=0 ; i < tuplesize ; i++) {
2147 it = PyTuple_GET_ITEM(lz->ittuple, i);
2148 item = (*Py_TYPE(it)->tp_iternext)(it);
2149 if (item == NULL) {
2150 Py_DECREF(result);
2151 return NULL;
2152 }
2153 olditem = PyTuple_GET_ITEM(result, i);
2154 PyTuple_SET_ITEM(result, i, item);
2155 Py_DECREF(olditem);
2156 }
2157 } else {
2158 result = PyTuple_New(tuplesize);
2159 if (result == NULL)
2160 return NULL;
2161 for (i=0 ; i < tuplesize ; i++) {
2162 it = PyTuple_GET_ITEM(lz->ittuple, i);
2163 item = (*Py_TYPE(it)->tp_iternext)(it);
2164 if (item == NULL) {
2165 Py_DECREF(result);
2166 return NULL;
2167 }
2168 PyTuple_SET_ITEM(result, i, item);
2169 }
2170 }
2171 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002172}
Barry Warsawbd599b52000-08-03 15:45:29 +00002173
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002174PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002175"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002176\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002177Return a zip object whose .__next__() method returns a tuple where\n\
2178the i-th element comes from the i-th iterable argument. The .__next__()\n\
2179method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002180is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002181
2182PyTypeObject PyZip_Type = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002183 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2184 "zip", /* tp_name */
2185 sizeof(zipobject), /* tp_basicsize */
2186 0, /* tp_itemsize */
2187 /* methods */
2188 (destructor)zip_dealloc, /* tp_dealloc */
2189 0, /* tp_print */
2190 0, /* tp_getattr */
2191 0, /* tp_setattr */
2192 0, /* tp_reserved */
2193 0, /* tp_repr */
2194 0, /* tp_as_number */
2195 0, /* tp_as_sequence */
2196 0, /* tp_as_mapping */
2197 0, /* tp_hash */
2198 0, /* tp_call */
2199 0, /* tp_str */
2200 PyObject_GenericGetAttr, /* tp_getattro */
2201 0, /* tp_setattro */
2202 0, /* tp_as_buffer */
2203 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2204 Py_TPFLAGS_BASETYPE, /* tp_flags */
2205 zip_doc, /* tp_doc */
2206 (traverseproc)zip_traverse, /* tp_traverse */
2207 0, /* tp_clear */
2208 0, /* tp_richcompare */
2209 0, /* tp_weaklistoffset */
2210 PyObject_SelfIter, /* tp_iter */
2211 (iternextfunc)zip_next, /* tp_iternext */
2212 0, /* tp_methods */
2213 0, /* tp_members */
2214 0, /* tp_getset */
2215 0, /* tp_base */
2216 0, /* tp_dict */
2217 0, /* tp_descr_get */
2218 0, /* tp_descr_set */
2219 0, /* tp_dictoffset */
2220 0, /* tp_init */
2221 PyType_GenericAlloc, /* tp_alloc */
2222 zip_new, /* tp_new */
2223 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002224};
Barry Warsawbd599b52000-08-03 15:45:29 +00002225
2226
Guido van Rossum79f25d91997-04-29 20:08:16 +00002227static PyMethodDef builtin_methods[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002228 {"__build_class__", (PyCFunction)builtin___build_class__,
2229 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2230 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2231 {"abs", builtin_abs, METH_O, abs_doc},
2232 {"all", builtin_all, METH_O, all_doc},
2233 {"any", builtin_any, METH_O, any_doc},
2234 {"ascii", builtin_ascii, METH_O, ascii_doc},
2235 {"bin", builtin_bin, METH_O, bin_doc},
2236 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2237 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2238 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2239 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2240 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2241 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2242 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2243 {"format", builtin_format, METH_VARARGS, format_doc},
2244 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2245 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2246 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2247 {"hash", builtin_hash, METH_O, hash_doc},
2248 {"hex", builtin_hex, METH_O, hex_doc},
2249 {"id", builtin_id, METH_O, id_doc},
2250 {"input", builtin_input, METH_VARARGS, input_doc},
2251 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2252 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2253 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2254 {"len", builtin_len, METH_O, len_doc},
2255 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2256 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2257 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2258 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2259 {"oct", builtin_oct, METH_O, oct_doc},
2260 {"ord", builtin_ord, METH_O, ord_doc},
2261 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2262 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2263 {"repr", builtin_repr, METH_O, repr_doc},
2264 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2265 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2266 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2267 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2268 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2269 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002270};
2271
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002272PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002273"Built-in functions, exceptions, and other objects.\n\
2274\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002275Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002276
Martin v. Löwis1a214512008-06-11 05:26:20 +00002277static struct PyModuleDef builtinsmodule = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002278 PyModuleDef_HEAD_INIT,
2279 "builtins",
2280 builtin_doc,
2281 -1, /* multiple "initialization" just copies the module dict. */
2282 builtin_methods,
2283 NULL,
2284 NULL,
2285 NULL,
2286 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002287};
2288
2289
Guido van Rossum25ce5661997-08-02 03:10:38 +00002290PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002291_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002292{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002293 PyObject *mod, *dict, *debug;
2294 mod = PyModule_Create(&builtinsmodule);
2295 if (mod == NULL)
2296 return NULL;
2297 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002298
Tim Peters7571a0f2003-03-23 17:52:28 +00002299#ifdef Py_TRACE_REFS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002300 /* "builtins" exposes a number of statically allocated objects
2301 * that, before this code was added in 2.3, never showed up in
2302 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2303 * result, programs leaking references to None and False (etc)
2304 * couldn't be diagnosed by examining sys.getobjects(0).
2305 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002306#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2307#else
2308#define ADD_TO_ALL(OBJECT) (void)0
2309#endif
2310
Tim Peters4b7625e2001-09-13 21:37:17 +00002311#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002312 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2313 return NULL; \
2314 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002315
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002316 SETBUILTIN("None", Py_None);
2317 SETBUILTIN("Ellipsis", Py_Ellipsis);
2318 SETBUILTIN("NotImplemented", Py_NotImplemented);
2319 SETBUILTIN("False", Py_False);
2320 SETBUILTIN("True", Py_True);
2321 SETBUILTIN("bool", &PyBool_Type);
2322 SETBUILTIN("memoryview", &PyMemoryView_Type);
2323 SETBUILTIN("bytearray", &PyByteArray_Type);
2324 SETBUILTIN("bytes", &PyBytes_Type);
2325 SETBUILTIN("classmethod", &PyClassMethod_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002326#ifndef WITHOUT_COMPLEX
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002327 SETBUILTIN("complex", &PyComplex_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002328#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002329 SETBUILTIN("dict", &PyDict_Type);
2330 SETBUILTIN("enumerate", &PyEnum_Type);
2331 SETBUILTIN("filter", &PyFilter_Type);
2332 SETBUILTIN("float", &PyFloat_Type);
2333 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2334 SETBUILTIN("property", &PyProperty_Type);
2335 SETBUILTIN("int", &PyLong_Type);
2336 SETBUILTIN("list", &PyList_Type);
2337 SETBUILTIN("map", &PyMap_Type);
2338 SETBUILTIN("object", &PyBaseObject_Type);
2339 SETBUILTIN("range", &PyRange_Type);
2340 SETBUILTIN("reversed", &PyReversed_Type);
2341 SETBUILTIN("set", &PySet_Type);
2342 SETBUILTIN("slice", &PySlice_Type);
2343 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2344 SETBUILTIN("str", &PyUnicode_Type);
2345 SETBUILTIN("super", &PySuper_Type);
2346 SETBUILTIN("tuple", &PyTuple_Type);
2347 SETBUILTIN("type", &PyType_Type);
2348 SETBUILTIN("zip", &PyZip_Type);
2349 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2350 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2351 Py_XDECREF(debug);
2352 return NULL;
2353 }
2354 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002355
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002356 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002357#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002358#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002359}