blob: cd851564063348e1c402c08f64f945cd2bc93c71 [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;
539 char *filename;
540 char *startstr;
541 int mode = -1;
542 int dont_inherit = 0;
543 int supplied_flags = 0;
544 int is_ast;
545 PyCompilerFlags cf;
546 PyObject *cmd;
547 static char *kwlist[] = {"source", "filename", "mode", "flags",
548 "dont_inherit", NULL};
549 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000550
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000551 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
552 kwlist, &cmd, &filename, &startstr,
553 &supplied_flags, &dont_inherit))
554 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000555
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000556 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000557
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000558 if (supplied_flags &
559 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
560 {
561 PyErr_SetString(PyExc_ValueError,
562 "compile(): unrecognised flags");
563 return NULL;
564 }
565 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000566
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000567 if (!dont_inherit) {
568 PyEval_MergeCompilerFlags(&cf);
569 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000570
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000571 if (strcmp(startstr, "exec") == 0)
572 mode = 0;
573 else if (strcmp(startstr, "eval") == 0)
574 mode = 1;
575 else if (strcmp(startstr, "single") == 0)
576 mode = 2;
577 else {
578 PyErr_SetString(PyExc_ValueError,
579 "compile() arg 3 must be 'exec', 'eval' or 'single'");
580 return NULL;
581 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000582
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000583 is_ast = PyAST_Check(cmd);
584 if (is_ast == -1)
585 return NULL;
586 if (is_ast) {
587 PyObject *result;
588 if (supplied_flags & PyCF_ONLY_AST) {
589 Py_INCREF(cmd);
590 result = cmd;
591 }
592 else {
593 PyArena *arena;
594 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000595
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000596 arena = PyArena_New();
597 mod = PyAST_obj2mod(cmd, arena, mode);
598 if (mod == NULL) {
599 PyArena_Free(arena);
600 return NULL;
601 }
602 result = (PyObject*)PyAST_Compile(mod, filename,
603 &cf, arena);
604 PyArena_Free(arena);
605 }
606 return result;
607 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000608
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000609 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
610 if (str == NULL)
611 return NULL;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000612
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000613 return Py_CompileStringFlags(str, filename, start[mode], &cf);
Guido van Rossum5b722181993-03-30 17:46:03 +0000614}
615
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000616PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000617"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000618\n\
619Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000620into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000621The filename will be used for run-time error messages.\n\
622The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000623single (interactive) statement, or 'eval' to compile an expression.\n\
624The flags argument, if present, controls which future statements influence\n\
625the compilation of the code.\n\
626The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
627the effects of any future statements in effect in the code calling\n\
628compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000629in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000630
Guido van Rossum79f25d91997-04-29 20:08:16 +0000631static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000632builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000633{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000634 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000635
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000636 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
637 return NULL;
638 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000639}
640
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000641PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000642"dir([object]) -> list of strings\n"
643"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000644"If called without an argument, return the names in the current scope.\n"
645"Else, return an alphabetized list of names comprising (some of) the attributes\n"
646"of the given object, and of attributes reachable from it.\n"
647"If the object supplies a method named __dir__, it will be used; otherwise\n"
648"the default dir() logic is used and returns:\n"
649" for a module object: the module's attributes.\n"
650" for a class object: its attributes, and recursively the attributes\n"
651" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000652" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000653" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000654
Guido van Rossum79f25d91997-04-29 20:08:16 +0000655static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000656builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000657{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000658 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000659
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000660 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
661 return NULL;
662 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000663}
664
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000665PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000666"divmod(x, y) -> (div, mod)\n\
667\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000668Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000669
670
Guido van Rossum79f25d91997-04-29 20:08:16 +0000671static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000672builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000673{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000674 PyObject *cmd, *result, *tmp = NULL;
675 PyObject *globals = Py_None, *locals = Py_None;
676 char *str;
677 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000678
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000679 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
680 return NULL;
681 if (locals != Py_None && !PyMapping_Check(locals)) {
682 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
683 return NULL;
684 }
685 if (globals != Py_None && !PyDict_Check(globals)) {
686 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
687 "globals must be a real dict; try eval(expr, {}, mapping)"
688 : "globals must be a dict");
689 return NULL;
690 }
691 if (globals == Py_None) {
692 globals = PyEval_GetGlobals();
693 if (locals == Py_None)
694 locals = PyEval_GetLocals();
695 }
696 else if (locals == Py_None)
697 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000698
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000699 if (globals == NULL || locals == NULL) {
700 PyErr_SetString(PyExc_TypeError,
701 "eval must be given globals and locals "
702 "when called without a frame");
703 return NULL;
704 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000705
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000706 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
707 if (PyDict_SetItemString(globals, "__builtins__",
708 PyEval_GetBuiltins()) != 0)
709 return NULL;
710 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000711
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000712 if (PyCode_Check(cmd)) {
713 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
714 PyErr_SetString(PyExc_TypeError,
715 "code object passed to eval() may not contain free variables");
716 return NULL;
717 }
718 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
719 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000720
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000721 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
722 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
723 if (str == NULL)
724 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000725
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000726 while (*str == ' ' || *str == '\t')
727 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000728
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000729 (void)PyEval_MergeCompilerFlags(&cf);
730 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
731 Py_XDECREF(tmp);
732 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000733}
734
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000735PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000736"eval(source[, globals[, locals]]) -> value\n\
737\n\
738Evaluate the source in the context of globals and locals.\n\
739The source may be a string representing a Python expression\n\
740or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000741The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000742defaulting to the current globals and locals.\n\
743If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000744
Georg Brandl7cae87c2006-09-06 06:51:57 +0000745static PyObject *
746builtin_exec(PyObject *self, PyObject *args)
747{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000748 PyObject *v;
749 PyObject *prog, *globals = Py_None, *locals = Py_None;
750 int plain = 0;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000751
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000752 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
753 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000754
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000755 if (globals == Py_None) {
756 globals = PyEval_GetGlobals();
757 if (locals == Py_None) {
758 locals = PyEval_GetLocals();
759 plain = 1;
760 }
761 if (!globals || !locals) {
762 PyErr_SetString(PyExc_SystemError,
763 "globals and locals cannot be NULL");
764 return NULL;
765 }
766 }
767 else if (locals == Py_None)
768 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000769
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000770 if (!PyDict_Check(globals)) {
771 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
772 globals->ob_type->tp_name);
773 return NULL;
774 }
775 if (!PyMapping_Check(locals)) {
776 PyErr_Format(PyExc_TypeError,
777 "arg 3 must be a mapping or None, not %.100s",
778 locals->ob_type->tp_name);
779 return NULL;
780 }
781 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
782 if (PyDict_SetItemString(globals, "__builtins__",
783 PyEval_GetBuiltins()) != 0)
784 return NULL;
785 }
786
787 if (PyCode_Check(prog)) {
788 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
789 PyErr_SetString(PyExc_TypeError,
790 "code object passed to exec() may not "
791 "contain free variables");
792 return NULL;
793 }
794 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
795 }
796 else {
797 char *str;
798 PyCompilerFlags cf;
799 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
800 str = source_as_string(prog, "exec",
801 "string, bytes or code", &cf);
802 if (str == NULL)
803 return NULL;
804 if (PyEval_MergeCompilerFlags(&cf))
805 v = PyRun_StringFlags(str, Py_file_input, globals,
806 locals, &cf);
807 else
808 v = PyRun_String(str, Py_file_input, globals, locals);
809 }
810 if (v == NULL)
811 return NULL;
812 Py_DECREF(v);
813 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000814}
815
816PyDoc_STRVAR(exec_doc,
817"exec(object[, globals[, locals]])\n\
818\n\
Mark Dickinson188aace2009-12-19 21:20:55 +0000819Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000820object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000821The globals and locals are dictionaries, defaulting to the current\n\
822globals and locals. If only globals is given, locals defaults to it.");
823
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000824
Guido van Rossum79f25d91997-04-29 20:08:16 +0000825static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000826builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000827{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000828 PyObject *v, *result, *dflt = NULL;
829 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000830
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000831 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
832 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000833
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000834 if (!PyUnicode_Check(name)) {
835 PyErr_SetString(PyExc_TypeError,
836 "getattr(): attribute name must be string");
837 return NULL;
838 }
839 result = PyObject_GetAttr(v, name);
840 if (result == NULL && dflt != NULL &&
841 PyErr_ExceptionMatches(PyExc_AttributeError))
842 {
843 PyErr_Clear();
844 Py_INCREF(dflt);
845 result = dflt;
846 }
847 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000848}
849
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000850PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000851"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000852\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000853Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
854When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000855exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000856
857
Guido van Rossum79f25d91997-04-29 20:08:16 +0000858static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000859builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000860{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000861 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000862
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000863 d = PyEval_GetGlobals();
864 Py_XINCREF(d);
865 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000866}
867
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000868PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000869"globals() -> dictionary\n\
870\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000871Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000872
873
Guido van Rossum79f25d91997-04-29 20:08:16 +0000874static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000875builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000876{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000877 PyObject *v;
878 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000879
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000880 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
881 return NULL;
882 if (!PyUnicode_Check(name)) {
883 PyErr_SetString(PyExc_TypeError,
884 "hasattr(): attribute name must be string");
885 return NULL;
886 }
887 v = PyObject_GetAttr(v, name);
888 if (v == NULL) {
889 if (!PyErr_ExceptionMatches(PyExc_Exception))
890 return NULL;
891 else {
892 PyErr_Clear();
893 Py_INCREF(Py_False);
894 return Py_False;
895 }
896 }
897 Py_DECREF(v);
898 Py_INCREF(Py_True);
899 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000900}
901
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000902PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000903"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000904\n\
905Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000906(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000907
908
Guido van Rossum79f25d91997-04-29 20:08:16 +0000909static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000910builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000911{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000912 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000913}
914
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000915PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000916"id(object) -> integer\n\
917\n\
918Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000919simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000920
921
Raymond Hettingera6c60372008-03-13 01:26:19 +0000922/* map object ************************************************************/
923
924typedef struct {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000925 PyObject_HEAD
926 PyObject *iters;
927 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000928} mapobject;
929
Guido van Rossum79f25d91997-04-29 20:08:16 +0000930static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000931map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000932{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000933 PyObject *it, *iters, *func;
934 mapobject *lz;
935 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000936
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000937 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
938 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000939
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000940 numargs = PyTuple_Size(args);
941 if (numargs < 2) {
942 PyErr_SetString(PyExc_TypeError,
943 "map() must have at least two arguments.");
944 return NULL;
945 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000946
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000947 iters = PyTuple_New(numargs-1);
948 if (iters == NULL)
949 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000950
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000951 for (i=1 ; i<numargs ; i++) {
952 /* Get iterator. */
953 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
954 if (it == NULL) {
955 Py_DECREF(iters);
956 return NULL;
957 }
958 PyTuple_SET_ITEM(iters, i-1, it);
959 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000960
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000961 /* create mapobject structure */
962 lz = (mapobject *)type->tp_alloc(type, 0);
963 if (lz == NULL) {
964 Py_DECREF(iters);
965 return NULL;
966 }
967 lz->iters = iters;
968 func = PyTuple_GET_ITEM(args, 0);
969 Py_INCREF(func);
970 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000971
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000972 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000973}
974
975static void
976map_dealloc(mapobject *lz)
977{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000978 PyObject_GC_UnTrack(lz);
979 Py_XDECREF(lz->iters);
980 Py_XDECREF(lz->func);
981 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +0000982}
983
984static int
985map_traverse(mapobject *lz, visitproc visit, void *arg)
986{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000987 Py_VISIT(lz->iters);
988 Py_VISIT(lz->func);
989 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000990}
991
992static PyObject *
993map_next(mapobject *lz)
994{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000995 PyObject *val;
996 PyObject *argtuple;
997 PyObject *result;
998 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000999
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001000 numargs = PyTuple_Size(lz->iters);
1001 argtuple = PyTuple_New(numargs);
1002 if (argtuple == NULL)
1003 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001004
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001005 for (i=0 ; i<numargs ; i++) {
1006 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1007 if (val == NULL) {
1008 Py_DECREF(argtuple);
1009 return NULL;
1010 }
1011 PyTuple_SET_ITEM(argtuple, i, val);
1012 }
1013 result = PyObject_Call(lz->func, argtuple, NULL);
1014 Py_DECREF(argtuple);
1015 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001016}
1017
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001018PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001019"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001020\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001021Make an iterator that computes the function using arguments from\n\
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001022each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001023
Raymond Hettingera6c60372008-03-13 01:26:19 +00001024PyTypeObject PyMap_Type = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001025 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1026 "map", /* tp_name */
1027 sizeof(mapobject), /* tp_basicsize */
1028 0, /* tp_itemsize */
1029 /* methods */
1030 (destructor)map_dealloc, /* tp_dealloc */
1031 0, /* tp_print */
1032 0, /* tp_getattr */
1033 0, /* tp_setattr */
1034 0, /* tp_reserved */
1035 0, /* tp_repr */
1036 0, /* tp_as_number */
1037 0, /* tp_as_sequence */
1038 0, /* tp_as_mapping */
1039 0, /* tp_hash */
1040 0, /* tp_call */
1041 0, /* tp_str */
1042 PyObject_GenericGetAttr, /* tp_getattro */
1043 0, /* tp_setattro */
1044 0, /* tp_as_buffer */
1045 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1046 Py_TPFLAGS_BASETYPE, /* tp_flags */
1047 map_doc, /* tp_doc */
1048 (traverseproc)map_traverse, /* tp_traverse */
1049 0, /* tp_clear */
1050 0, /* tp_richcompare */
1051 0, /* tp_weaklistoffset */
1052 PyObject_SelfIter, /* tp_iter */
1053 (iternextfunc)map_next, /* tp_iternext */
1054 0, /* tp_methods */
1055 0, /* tp_members */
1056 0, /* tp_getset */
1057 0, /* tp_base */
1058 0, /* tp_dict */
1059 0, /* tp_descr_get */
1060 0, /* tp_descr_set */
1061 0, /* tp_dictoffset */
1062 0, /* tp_init */
1063 PyType_GenericAlloc, /* tp_alloc */
1064 map_new, /* tp_new */
1065 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001066};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001067
Guido van Rossum79f25d91997-04-29 20:08:16 +00001068static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001069builtin_next(PyObject *self, PyObject *args)
1070{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001071 PyObject *it, *res;
1072 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001073
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001074 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1075 return NULL;
1076 if (!PyIter_Check(it)) {
1077 PyErr_Format(PyExc_TypeError,
1078 "%.200s object is not an iterator",
1079 it->ob_type->tp_name);
1080 return NULL;
1081 }
1082
1083 res = (*it->ob_type->tp_iternext)(it);
1084 if (res != NULL) {
1085 return res;
1086 } else if (def != NULL) {
1087 if (PyErr_Occurred()) {
1088 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1089 return NULL;
1090 PyErr_Clear();
1091 }
1092 Py_INCREF(def);
1093 return def;
1094 } else if (PyErr_Occurred()) {
1095 return NULL;
1096 } else {
1097 PyErr_SetNone(PyExc_StopIteration);
1098 return NULL;
1099 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001100}
1101
1102PyDoc_STRVAR(next_doc,
1103"next(iterator[, default])\n\
1104\n\
1105Return the next item from the iterator. If default is given and the iterator\n\
1106is exhausted, it is returned instead of raising StopIteration.");
1107
1108
1109static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001110builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001111{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001112 PyObject *v;
1113 PyObject *name;
1114 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001115
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001116 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1117 return NULL;
1118 if (PyObject_SetAttr(v, name, value) != 0)
1119 return NULL;
1120 Py_INCREF(Py_None);
1121 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001122}
1123
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001124PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001125"setattr(object, name, value)\n\
1126\n\
1127Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001128``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001129
1130
Guido van Rossum79f25d91997-04-29 20:08:16 +00001131static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001132builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001133{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001134 PyObject *v;
1135 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001136
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001137 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1138 return NULL;
1139 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1140 return NULL;
1141 Py_INCREF(Py_None);
1142 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001143}
1144
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001145PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001146"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001147\n\
1148Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001149``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001150
1151
Guido van Rossum79f25d91997-04-29 20:08:16 +00001152static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001153builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001154{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001155 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001156
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001157 x = PyObject_Hash(v);
1158 if (x == -1)
1159 return NULL;
1160 return PyLong_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001161}
1162
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001163PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001164"hash(object) -> integer\n\
1165\n\
1166Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001167the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001168
1169
Guido van Rossum79f25d91997-04-29 20:08:16 +00001170static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001171builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001172{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001173 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001174}
1175
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001176PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001177"hex(number) -> string\n\
1178\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001179Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001180
1181
Guido van Rossum79f25d91997-04-29 20:08:16 +00001182static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001183builtin_iter(PyObject *self, PyObject *args)
1184{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001185 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001186
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001187 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1188 return NULL;
1189 if (w == NULL)
1190 return PyObject_GetIter(v);
1191 if (!PyCallable_Check(v)) {
1192 PyErr_SetString(PyExc_TypeError,
1193 "iter(v, w): v must be callable");
1194 return NULL;
1195 }
1196 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001197}
1198
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001199PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001200"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001201iter(callable, sentinel) -> iterator\n\
1202\n\
1203Get an iterator from an object. In the first form, the argument must\n\
1204supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001205In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001206
1207
1208static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001209builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001210{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001211 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001212
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001213 res = PyObject_Size(v);
1214 if (res < 0 && PyErr_Occurred())
1215 return NULL;
1216 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001217}
1218
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001219PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001220"len(object) -> integer\n\
1221\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001222Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001223
1224
Guido van Rossum79f25d91997-04-29 20:08:16 +00001225static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001226builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001227{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001228 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001229
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001230 d = PyEval_GetLocals();
1231 Py_XINCREF(d);
1232 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001233}
1234
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001235PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001236"locals() -> dictionary\n\
1237\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001238Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001239
1240
Guido van Rossum79f25d91997-04-29 20:08:16 +00001241static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001242min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001243{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001244 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1245 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001246
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001247 if (PyTuple_Size(args) > 1)
1248 v = args;
1249 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1250 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001251
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001252 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1253 keyfunc = PyDict_GetItemString(kwds, "key");
1254 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1255 PyErr_Format(PyExc_TypeError,
1256 "%s() got an unexpected keyword argument", name);
1257 return NULL;
1258 }
1259 Py_INCREF(keyfunc);
1260 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001261
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001262 it = PyObject_GetIter(v);
1263 if (it == NULL) {
1264 Py_XDECREF(keyfunc);
1265 return NULL;
1266 }
Tim Petersc3074532001-05-03 07:00:32 +00001267
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001268 maxitem = NULL; /* the result */
1269 maxval = NULL; /* the value associated with the result */
1270 while (( item = PyIter_Next(it) )) {
1271 /* get the value from the key function */
1272 if (keyfunc != NULL) {
1273 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1274 if (val == NULL)
1275 goto Fail_it_item;
1276 }
1277 /* no key function; the value is the item */
1278 else {
1279 val = item;
1280 Py_INCREF(val);
1281 }
Tim Petersc3074532001-05-03 07:00:32 +00001282
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001283 /* maximum value and item are unset; set them */
1284 if (maxval == NULL) {
1285 maxitem = item;
1286 maxval = val;
1287 }
1288 /* maximum value and item are set; update them as necessary */
1289 else {
1290 int cmp = PyObject_RichCompareBool(val, maxval, op);
1291 if (cmp < 0)
1292 goto Fail_it_item_and_val;
1293 else if (cmp > 0) {
1294 Py_DECREF(maxval);
1295 Py_DECREF(maxitem);
1296 maxval = val;
1297 maxitem = item;
1298 }
1299 else {
1300 Py_DECREF(item);
1301 Py_DECREF(val);
1302 }
1303 }
1304 }
1305 if (PyErr_Occurred())
1306 goto Fail_it;
1307 if (maxval == NULL) {
1308 PyErr_Format(PyExc_ValueError,
1309 "%s() arg is an empty sequence", name);
1310 assert(maxitem == NULL);
1311 }
1312 else
1313 Py_DECREF(maxval);
1314 Py_DECREF(it);
1315 Py_XDECREF(keyfunc);
1316 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001317
1318Fail_it_item_and_val:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001319 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001320Fail_it_item:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001321 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001322Fail_it:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001323 Py_XDECREF(maxval);
1324 Py_XDECREF(maxitem);
1325 Py_DECREF(it);
1326 Py_XDECREF(keyfunc);
1327 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001328}
1329
Guido van Rossum79f25d91997-04-29 20:08:16 +00001330static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001331builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001332{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001333 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001334}
1335
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001336PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001337"min(iterable[, key=func]) -> value\n\
1338min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001339\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001340With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001341With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001342
1343
Guido van Rossum79f25d91997-04-29 20:08:16 +00001344static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001345builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001346{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001347 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001348}
1349
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001350PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001351"max(iterable[, key=func]) -> value\n\
1352max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001353\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001354With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001355With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001356
1357
Guido van Rossum79f25d91997-04-29 20:08:16 +00001358static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001359builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001360{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001361 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001362}
1363
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001364PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001365"oct(number) -> string\n\
1366\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001367Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001368
1369
Guido van Rossum79f25d91997-04-29 20:08:16 +00001370static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001371builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001372{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001373 long ord;
1374 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001375
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001376 if (PyBytes_Check(obj)) {
1377 size = PyBytes_GET_SIZE(obj);
1378 if (size == 1) {
1379 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1380 return PyLong_FromLong(ord);
1381 }
1382 }
1383 else if (PyUnicode_Check(obj)) {
1384 size = PyUnicode_GET_SIZE(obj);
1385 if (size == 1) {
1386 ord = (long)*PyUnicode_AS_UNICODE(obj);
1387 return PyLong_FromLong(ord);
1388 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001389#ifndef Py_UNICODE_WIDE
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001390 if (size == 2) {
1391 /* Decode a valid surrogate pair */
1392 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1393 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1394 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1395 0xDC00 <= c1 && c1 <= 0xDFFF) {
1396 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1397 0x00010000);
1398 return PyLong_FromLong(ord);
1399 }
1400 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001401#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001402 }
1403 else if (PyByteArray_Check(obj)) {
1404 /* XXX Hopefully this is temporary */
1405 size = PyByteArray_GET_SIZE(obj);
1406 if (size == 1) {
1407 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1408 return PyLong_FromLong(ord);
1409 }
1410 }
1411 else {
1412 PyErr_Format(PyExc_TypeError,
1413 "ord() expected string of length 1, but " \
1414 "%.200s found", obj->ob_type->tp_name);
1415 return NULL;
1416 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001417
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001418 PyErr_Format(PyExc_TypeError,
1419 "ord() expected a character, "
1420 "but string of length %zd found",
1421 size);
1422 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001423}
1424
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001425PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001426"ord(c) -> integer\n\
1427\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001428Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001429)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001430#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001431PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001432"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001433)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001434#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001435;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001436
1437
Guido van Rossum79f25d91997-04-29 20:08:16 +00001438static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001439builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001440{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001441 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001442
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001443 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1444 return NULL;
1445 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001446}
1447
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001448PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001449"pow(x, y[, z]) -> number\n\
1450\n\
1451With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001452equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001453
1454
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001455
Guido van Rossum34343512006-11-30 22:13:52 +00001456static PyObject *
1457builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1458{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001459 static char *kwlist[] = {"sep", "end", "file", 0};
1460 static PyObject *dummy_args;
1461 PyObject *sep = NULL, *end = NULL, *file = NULL;
1462 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001463
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001464 if (dummy_args == NULL) {
1465 if (!(dummy_args = PyTuple_New(0)))
1466 return NULL;
1467 }
1468 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1469 kwlist, &sep, &end, &file))
1470 return NULL;
1471 if (file == NULL || file == Py_None) {
1472 file = PySys_GetObject("stdout");
1473 /* sys.stdout may be None when FILE* stdout isn't connected */
1474 if (file == Py_None)
1475 Py_RETURN_NONE;
1476 }
Guido van Rossum34343512006-11-30 22:13:52 +00001477
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001478 if (sep && sep != Py_None && !PyUnicode_Check(sep)) {
1479 PyErr_Format(PyExc_TypeError,
1480 "sep must be None or a string, not %.200s",
1481 sep->ob_type->tp_name);
1482 return NULL;
1483 }
1484 if (end && end != Py_None && !PyUnicode_Check(end)) {
1485 PyErr_Format(PyExc_TypeError,
1486 "end must be None or a string, not %.200s",
1487 end->ob_type->tp_name);
1488 return NULL;
1489 }
Guido van Rossum34343512006-11-30 22:13:52 +00001490
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001491 for (i = 0; i < PyTuple_Size(args); i++) {
1492 if (i > 0) {
1493 if (sep == NULL || sep == Py_None)
1494 err = PyFile_WriteString(" ", file);
1495 else
1496 err = PyFile_WriteObject(sep, file,
1497 Py_PRINT_RAW);
1498 if (err)
1499 return NULL;
1500 }
1501 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1502 Py_PRINT_RAW);
1503 if (err)
1504 return NULL;
1505 }
Guido van Rossum34343512006-11-30 22:13:52 +00001506
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001507 if (end == NULL || end == Py_None)
1508 err = PyFile_WriteString("\n", file);
1509 else
1510 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1511 if (err)
1512 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001513
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001514 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001515}
1516
1517PyDoc_STRVAR(print_doc,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001518"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001519\n\
1520Prints the values to a stream, or to sys.stdout by default.\n\
1521Optional keyword arguments:\n\
1522file: a file-like object (stream); defaults to the current sys.stdout.\n\
1523sep: string inserted between values, default a space.\n\
1524end: string appended after the last value, default a newline.");
1525
1526
Guido van Rossuma88a0332007-02-26 16:59:55 +00001527static PyObject *
1528builtin_input(PyObject *self, PyObject *args)
1529{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001530 PyObject *promptarg = NULL;
1531 PyObject *fin = PySys_GetObject("stdin");
1532 PyObject *fout = PySys_GetObject("stdout");
1533 PyObject *ferr = PySys_GetObject("stderr");
1534 PyObject *tmp;
1535 long fd;
1536 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001537
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001538 /* Parse arguments */
1539 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1540 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001541
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001542 /* Check that stdin/out/err are intact */
1543 if (fin == NULL || fin == Py_None) {
1544 PyErr_SetString(PyExc_RuntimeError,
1545 "input(): lost sys.stdin");
1546 return NULL;
1547 }
1548 if (fout == NULL || fout == Py_None) {
1549 PyErr_SetString(PyExc_RuntimeError,
1550 "input(): lost sys.stdout");
1551 return NULL;
1552 }
1553 if (ferr == NULL || ferr == Py_None) {
1554 PyErr_SetString(PyExc_RuntimeError,
1555 "input(): lost sys.stderr");
1556 return NULL;
1557 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001558
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001559 /* First of all, flush stderr */
1560 tmp = PyObject_CallMethod(ferr, "flush", "");
1561 if (tmp == NULL)
1562 PyErr_Clear();
1563 else
1564 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001565
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001566 /* We should only use (GNU) readline if Python's sys.stdin and
1567 sys.stdout are the same as C's stdin and stdout, because we
1568 need to pass it those. */
1569 tmp = PyObject_CallMethod(fin, "fileno", "");
1570 if (tmp == NULL) {
1571 PyErr_Clear();
1572 tty = 0;
1573 }
1574 else {
1575 fd = PyLong_AsLong(tmp);
1576 Py_DECREF(tmp);
1577 if (fd < 0 && PyErr_Occurred())
1578 return NULL;
1579 tty = fd == fileno(stdin) && isatty(fd);
1580 }
1581 if (tty) {
1582 tmp = PyObject_CallMethod(fout, "fileno", "");
1583 if (tmp == NULL)
1584 PyErr_Clear();
1585 else {
1586 fd = PyLong_AsLong(tmp);
1587 Py_DECREF(tmp);
1588 if (fd < 0 && PyErr_Occurred())
1589 return NULL;
1590 tty = fd == fileno(stdout) && isatty(fd);
1591 }
1592 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001593
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001594 /* If we're interactive, use (GNU) readline */
1595 if (tty) {
1596 PyObject *po;
1597 char *prompt;
1598 char *s;
1599 PyObject *stdin_encoding;
1600 PyObject *result;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001601
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001602 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1603 if (!stdin_encoding)
1604 /* stdin is a text stream, so it must have an
1605 encoding. */
1606 return NULL;
1607 tmp = PyObject_CallMethod(fout, "flush", "");
1608 if (tmp == NULL)
1609 PyErr_Clear();
1610 else
1611 Py_DECREF(tmp);
1612 if (promptarg != NULL) {
1613 PyObject *stringpo;
1614 PyObject *stdout_encoding;
1615 stdout_encoding = PyObject_GetAttrString(fout,
1616 "encoding");
1617 if (stdout_encoding == NULL) {
1618 Py_DECREF(stdin_encoding);
1619 return NULL;
1620 }
1621 stringpo = PyObject_Str(promptarg);
1622 if (stringpo == NULL) {
1623 Py_DECREF(stdin_encoding);
1624 Py_DECREF(stdout_encoding);
1625 return NULL;
1626 }
1627 po = PyUnicode_AsEncodedString(stringpo,
1628 _PyUnicode_AsString(stdout_encoding), NULL);
1629 Py_DECREF(stdout_encoding);
1630 Py_DECREF(stringpo);
1631 if (po == NULL) {
1632 Py_DECREF(stdin_encoding);
1633 return NULL;
1634 }
1635 prompt = PyBytes_AsString(po);
1636 if (prompt == NULL) {
1637 Py_DECREF(stdin_encoding);
1638 Py_DECREF(po);
1639 return NULL;
1640 }
1641 }
1642 else {
1643 po = NULL;
1644 prompt = "";
1645 }
1646 s = PyOS_Readline(stdin, stdout, prompt);
1647 Py_XDECREF(po);
1648 if (s == NULL) {
1649 if (!PyErr_Occurred())
1650 PyErr_SetNone(PyExc_KeyboardInterrupt);
1651 Py_DECREF(stdin_encoding);
1652 return NULL;
1653 }
1654 if (*s == '\0') {
1655 PyErr_SetNone(PyExc_EOFError);
1656 result = NULL;
1657 }
1658 else { /* strip trailing '\n' */
1659 size_t len = strlen(s);
1660 if (len > PY_SSIZE_T_MAX) {
1661 PyErr_SetString(PyExc_OverflowError,
1662 "input: input too long");
1663 result = NULL;
1664 }
1665 else {
1666 result = PyUnicode_Decode
1667 (s, len-1,
1668 _PyUnicode_AsString(stdin_encoding),
1669 NULL);
1670 }
1671 }
1672 Py_DECREF(stdin_encoding);
1673 PyMem_FREE(s);
1674 return result;
1675 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001676
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001677 /* Fallback if we're not interactive */
1678 if (promptarg != NULL) {
1679 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1680 return NULL;
1681 }
1682 tmp = PyObject_CallMethod(fout, "flush", "");
1683 if (tmp == NULL)
1684 PyErr_Clear();
1685 else
1686 Py_DECREF(tmp);
1687 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001688}
1689
1690PyDoc_STRVAR(input_doc,
1691"input([prompt]) -> string\n\
1692\n\
1693Read a string from standard input. The trailing newline is stripped.\n\
1694If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1695On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1696is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001697
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001698
Guido van Rossum79f25d91997-04-29 20:08:16 +00001699static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001700builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001701{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001702 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001703}
1704
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001705PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001706"repr(object) -> string\n\
1707\n\
1708Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001709For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001710
1711
Guido van Rossum79f25d91997-04-29 20:08:16 +00001712static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001713builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001714{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001715 static PyObject *round_str = NULL;
1716 PyObject *ndigits = NULL;
1717 static char *kwlist[] = {"number", "ndigits", 0};
1718 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001719
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001720 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1721 kwlist, &number, &ndigits))
1722 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001723
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001724 if (Py_TYPE(number)->tp_dict == NULL) {
1725 if (PyType_Ready(Py_TYPE(number)) < 0)
1726 return NULL;
1727 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001728
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001729 if (round_str == NULL) {
1730 round_str = PyUnicode_InternFromString("__round__");
1731 if (round_str == NULL)
1732 return NULL;
1733 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001734
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001735 round = _PyType_Lookup(Py_TYPE(number), round_str);
1736 if (round == NULL) {
1737 PyErr_Format(PyExc_TypeError,
1738 "type %.100s doesn't define __round__ method",
1739 Py_TYPE(number)->tp_name);
1740 return NULL;
1741 }
Alex Martelliae211f92007-08-22 23:21:33 +00001742
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001743 if (ndigits == NULL)
1744 return PyObject_CallFunction(round, "O", number);
1745 else
1746 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001747}
1748
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001749PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001750"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001751\n\
1752Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001753This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001754same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001755
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001756
Raymond Hettinger64958a12003-12-17 20:43:33 +00001757static PyObject *
1758builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1759{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001760 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1761 PyObject *callable;
1762 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1763 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001764
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001765 /* args 1-3 should match listsort in Objects/listobject.c */
1766 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1767 kwlist, &seq, &keyfunc, &reverse))
1768 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001769
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001770 newlist = PySequence_List(seq);
1771 if (newlist == NULL)
1772 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001773
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001774 callable = PyObject_GetAttrString(newlist, "sort");
1775 if (callable == NULL) {
1776 Py_DECREF(newlist);
1777 return NULL;
1778 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001779
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001780 newargs = PyTuple_GetSlice(args, 1, 4);
1781 if (newargs == NULL) {
1782 Py_DECREF(newlist);
1783 Py_DECREF(callable);
1784 return NULL;
1785 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001786
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001787 v = PyObject_Call(callable, newargs, kwds);
1788 Py_DECREF(newargs);
1789 Py_DECREF(callable);
1790 if (v == NULL) {
1791 Py_DECREF(newlist);
1792 return NULL;
1793 }
1794 Py_DECREF(v);
1795 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001796}
1797
1798PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001799"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001800
Guido van Rossum79f25d91997-04-29 20:08:16 +00001801static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001802builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001803{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001804 PyObject *v = NULL;
1805 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001806
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001807 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1808 return NULL;
1809 if (v == NULL) {
1810 d = PyEval_GetLocals();
1811 if (d == NULL) {
1812 if (!PyErr_Occurred())
1813 PyErr_SetString(PyExc_SystemError,
1814 "vars(): no locals!?");
1815 }
1816 else
1817 Py_INCREF(d);
1818 }
1819 else {
1820 d = PyObject_GetAttrString(v, "__dict__");
1821 if (d == NULL) {
1822 PyErr_SetString(PyExc_TypeError,
1823 "vars() argument must have __dict__ attribute");
1824 return NULL;
1825 }
1826 }
1827 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001828}
1829
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001830PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001831"vars([object]) -> dictionary\n\
1832\n\
1833Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001834With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001835
Alex Martellia70b1912003-04-22 08:12:33 +00001836static PyObject*
1837builtin_sum(PyObject *self, PyObject *args)
1838{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001839 PyObject *seq;
1840 PyObject *result = NULL;
1841 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001842
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001843 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1844 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001845
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001846 iter = PyObject_GetIter(seq);
1847 if (iter == NULL)
1848 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001849
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001850 if (result == NULL) {
1851 result = PyLong_FromLong(0);
1852 if (result == NULL) {
1853 Py_DECREF(iter);
1854 return NULL;
1855 }
1856 } else {
1857 /* reject string values for 'start' parameter */
1858 if (PyUnicode_Check(result)) {
1859 PyErr_SetString(PyExc_TypeError,
1860 "sum() can't sum strings [use ''.join(seq) instead]");
1861 Py_DECREF(iter);
1862 return NULL;
1863 }
1864 if (PyByteArray_Check(result)) {
1865 PyErr_SetString(PyExc_TypeError,
1866 "sum() can't sum bytes [use b''.join(seq) instead]");
1867 Py_DECREF(iter);
1868 return NULL;
1869 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001870
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001871 Py_INCREF(result);
1872 }
Alex Martellia70b1912003-04-22 08:12:33 +00001873
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001874#ifndef SLOW_SUM
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001875 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1876 Assumes all inputs are the same type. If the assumption fails, default
1877 to the more general routine.
1878 */
1879 if (PyLong_CheckExact(result)) {
1880 int overflow;
1881 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1882 /* If this already overflowed, don't even enter the loop. */
1883 if (overflow == 0) {
1884 Py_DECREF(result);
1885 result = NULL;
1886 }
1887 while(result == NULL) {
1888 item = PyIter_Next(iter);
1889 if (item == NULL) {
1890 Py_DECREF(iter);
1891 if (PyErr_Occurred())
1892 return NULL;
1893 return PyLong_FromLong(i_result);
1894 }
1895 if (PyLong_CheckExact(item)) {
1896 long b = PyLong_AsLongAndOverflow(item, &overflow);
1897 long x = i_result + b;
1898 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1899 i_result = x;
1900 Py_DECREF(item);
1901 continue;
1902 }
1903 }
1904 /* Either overflowed or is not an int. Restore real objects and process normally */
1905 result = PyLong_FromLong(i_result);
1906 temp = PyNumber_Add(result, item);
1907 Py_DECREF(result);
1908 Py_DECREF(item);
1909 result = temp;
1910 if (result == NULL) {
1911 Py_DECREF(iter);
1912 return NULL;
1913 }
1914 }
1915 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001916
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001917 if (PyFloat_CheckExact(result)) {
1918 double f_result = PyFloat_AS_DOUBLE(result);
1919 Py_DECREF(result);
1920 result = NULL;
1921 while(result == NULL) {
1922 item = PyIter_Next(iter);
1923 if (item == NULL) {
1924 Py_DECREF(iter);
1925 if (PyErr_Occurred())
1926 return NULL;
1927 return PyFloat_FromDouble(f_result);
1928 }
1929 if (PyFloat_CheckExact(item)) {
1930 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1931 f_result += PyFloat_AS_DOUBLE(item);
1932 PyFPE_END_PROTECT(f_result)
1933 Py_DECREF(item);
1934 continue;
1935 }
1936 if (PyLong_CheckExact(item)) {
1937 long value;
1938 int overflow;
1939 value = PyLong_AsLongAndOverflow(item, &overflow);
1940 if (!overflow) {
1941 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1942 f_result += (double)value;
1943 PyFPE_END_PROTECT(f_result)
1944 Py_DECREF(item);
1945 continue;
1946 }
1947 }
1948 result = PyFloat_FromDouble(f_result);
1949 temp = PyNumber_Add(result, item);
1950 Py_DECREF(result);
1951 Py_DECREF(item);
1952 result = temp;
1953 if (result == NULL) {
1954 Py_DECREF(iter);
1955 return NULL;
1956 }
1957 }
1958 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001959#endif
1960
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001961 for(;;) {
1962 item = PyIter_Next(iter);
1963 if (item == NULL) {
1964 /* error, or end-of-sequence */
1965 if (PyErr_Occurred()) {
1966 Py_DECREF(result);
1967 result = NULL;
1968 }
1969 break;
1970 }
1971 temp = PyNumber_Add(result, item);
1972 Py_DECREF(result);
1973 Py_DECREF(item);
1974 result = temp;
1975 if (result == NULL)
1976 break;
1977 }
1978 Py_DECREF(iter);
1979 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00001980}
1981
1982PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001983"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00001984\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00001985Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
1986of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00001987empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00001988
1989
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001990static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001991builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001992{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001993 PyObject *inst;
1994 PyObject *cls;
1995 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001996
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001997 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
1998 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00001999
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002000 retval = PyObject_IsInstance(inst, cls);
2001 if (retval < 0)
2002 return NULL;
2003 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002004}
2005
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002006PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002007"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002008\n\
2009Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002010With a type as second argument, return whether that is the object's type.\n\
2011The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002012isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002013
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002014
2015static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002016builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002017{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002018 PyObject *derived;
2019 PyObject *cls;
2020 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002021
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002022 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2023 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002024
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002025 retval = PyObject_IsSubclass(derived, cls);
2026 if (retval < 0)
2027 return NULL;
2028 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002029}
2030
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002031PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002032"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002033\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002034Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2035When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2036is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002037
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002038
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002039typedef struct {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002040 PyObject_HEAD
2041 Py_ssize_t tuplesize;
2042 PyObject *ittuple; /* tuple of iterators */
2043 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002044} zipobject;
2045
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002046static PyObject *
2047zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002048{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002049 zipobject *lz;
2050 Py_ssize_t i;
2051 PyObject *ittuple; /* tuple of iterators */
2052 PyObject *result;
2053 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002054
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002055 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2056 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002057
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002058 /* args must be a tuple */
2059 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002060
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002061 /* obtain iterators */
2062 ittuple = PyTuple_New(tuplesize);
2063 if (ittuple == NULL)
2064 return NULL;
2065 for (i=0; i < tuplesize; ++i) {
2066 PyObject *item = PyTuple_GET_ITEM(args, i);
2067 PyObject *it = PyObject_GetIter(item);
2068 if (it == NULL) {
2069 if (PyErr_ExceptionMatches(PyExc_TypeError))
2070 PyErr_Format(PyExc_TypeError,
2071 "zip argument #%zd must support iteration",
2072 i+1);
2073 Py_DECREF(ittuple);
2074 return NULL;
2075 }
2076 PyTuple_SET_ITEM(ittuple, i, it);
2077 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002078
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002079 /* create a result holder */
2080 result = PyTuple_New(tuplesize);
2081 if (result == NULL) {
2082 Py_DECREF(ittuple);
2083 return NULL;
2084 }
2085 for (i=0 ; i < tuplesize ; i++) {
2086 Py_INCREF(Py_None);
2087 PyTuple_SET_ITEM(result, i, Py_None);
2088 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002089
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002090 /* create zipobject structure */
2091 lz = (zipobject *)type->tp_alloc(type, 0);
2092 if (lz == NULL) {
2093 Py_DECREF(ittuple);
2094 Py_DECREF(result);
2095 return NULL;
2096 }
2097 lz->ittuple = ittuple;
2098 lz->tuplesize = tuplesize;
2099 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002100
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002101 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002102}
2103
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002104static void
2105zip_dealloc(zipobject *lz)
2106{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002107 PyObject_GC_UnTrack(lz);
2108 Py_XDECREF(lz->ittuple);
2109 Py_XDECREF(lz->result);
2110 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002111}
2112
2113static int
2114zip_traverse(zipobject *lz, visitproc visit, void *arg)
2115{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002116 Py_VISIT(lz->ittuple);
2117 Py_VISIT(lz->result);
2118 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002119}
2120
2121static PyObject *
2122zip_next(zipobject *lz)
2123{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002124 Py_ssize_t i;
2125 Py_ssize_t tuplesize = lz->tuplesize;
2126 PyObject *result = lz->result;
2127 PyObject *it;
2128 PyObject *item;
2129 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002130
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002131 if (tuplesize == 0)
2132 return NULL;
2133 if (Py_REFCNT(result) == 1) {
2134 Py_INCREF(result);
2135 for (i=0 ; i < tuplesize ; i++) {
2136 it = PyTuple_GET_ITEM(lz->ittuple, i);
2137 item = (*Py_TYPE(it)->tp_iternext)(it);
2138 if (item == NULL) {
2139 Py_DECREF(result);
2140 return NULL;
2141 }
2142 olditem = PyTuple_GET_ITEM(result, i);
2143 PyTuple_SET_ITEM(result, i, item);
2144 Py_DECREF(olditem);
2145 }
2146 } else {
2147 result = PyTuple_New(tuplesize);
2148 if (result == NULL)
2149 return NULL;
2150 for (i=0 ; i < tuplesize ; i++) {
2151 it = PyTuple_GET_ITEM(lz->ittuple, i);
2152 item = (*Py_TYPE(it)->tp_iternext)(it);
2153 if (item == NULL) {
2154 Py_DECREF(result);
2155 return NULL;
2156 }
2157 PyTuple_SET_ITEM(result, i, item);
2158 }
2159 }
2160 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002161}
Barry Warsawbd599b52000-08-03 15:45:29 +00002162
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002163PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002164"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002165\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002166Return a zip object whose .__next__() method returns a tuple where\n\
2167the i-th element comes from the i-th iterable argument. The .__next__()\n\
2168method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002169is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002170
2171PyTypeObject PyZip_Type = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002172 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2173 "zip", /* tp_name */
2174 sizeof(zipobject), /* tp_basicsize */
2175 0, /* tp_itemsize */
2176 /* methods */
2177 (destructor)zip_dealloc, /* tp_dealloc */
2178 0, /* tp_print */
2179 0, /* tp_getattr */
2180 0, /* tp_setattr */
2181 0, /* tp_reserved */
2182 0, /* tp_repr */
2183 0, /* tp_as_number */
2184 0, /* tp_as_sequence */
2185 0, /* tp_as_mapping */
2186 0, /* tp_hash */
2187 0, /* tp_call */
2188 0, /* tp_str */
2189 PyObject_GenericGetAttr, /* tp_getattro */
2190 0, /* tp_setattro */
2191 0, /* tp_as_buffer */
2192 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2193 Py_TPFLAGS_BASETYPE, /* tp_flags */
2194 zip_doc, /* tp_doc */
2195 (traverseproc)zip_traverse, /* tp_traverse */
2196 0, /* tp_clear */
2197 0, /* tp_richcompare */
2198 0, /* tp_weaklistoffset */
2199 PyObject_SelfIter, /* tp_iter */
2200 (iternextfunc)zip_next, /* tp_iternext */
2201 0, /* tp_methods */
2202 0, /* tp_members */
2203 0, /* tp_getset */
2204 0, /* tp_base */
2205 0, /* tp_dict */
2206 0, /* tp_descr_get */
2207 0, /* tp_descr_set */
2208 0, /* tp_dictoffset */
2209 0, /* tp_init */
2210 PyType_GenericAlloc, /* tp_alloc */
2211 zip_new, /* tp_new */
2212 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002213};
Barry Warsawbd599b52000-08-03 15:45:29 +00002214
2215
Guido van Rossum79f25d91997-04-29 20:08:16 +00002216static PyMethodDef builtin_methods[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002217 {"__build_class__", (PyCFunction)builtin___build_class__,
2218 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2219 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2220 {"abs", builtin_abs, METH_O, abs_doc},
2221 {"all", builtin_all, METH_O, all_doc},
2222 {"any", builtin_any, METH_O, any_doc},
2223 {"ascii", builtin_ascii, METH_O, ascii_doc},
2224 {"bin", builtin_bin, METH_O, bin_doc},
2225 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2226 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2227 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2228 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2229 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2230 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2231 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2232 {"format", builtin_format, METH_VARARGS, format_doc},
2233 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2234 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2235 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2236 {"hash", builtin_hash, METH_O, hash_doc},
2237 {"hex", builtin_hex, METH_O, hex_doc},
2238 {"id", builtin_id, METH_O, id_doc},
2239 {"input", builtin_input, METH_VARARGS, input_doc},
2240 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2241 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2242 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2243 {"len", builtin_len, METH_O, len_doc},
2244 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2245 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2246 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2247 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2248 {"oct", builtin_oct, METH_O, oct_doc},
2249 {"ord", builtin_ord, METH_O, ord_doc},
2250 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2251 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2252 {"repr", builtin_repr, METH_O, repr_doc},
2253 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2254 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2255 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2256 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2257 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2258 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002259};
2260
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002261PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002262"Built-in functions, exceptions, and other objects.\n\
2263\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002264Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002265
Martin v. Löwis1a214512008-06-11 05:26:20 +00002266static struct PyModuleDef builtinsmodule = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002267 PyModuleDef_HEAD_INIT,
2268 "builtins",
2269 builtin_doc,
2270 -1, /* multiple "initialization" just copies the module dict. */
2271 builtin_methods,
2272 NULL,
2273 NULL,
2274 NULL,
2275 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002276};
2277
2278
Guido van Rossum25ce5661997-08-02 03:10:38 +00002279PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002280_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002281{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002282 PyObject *mod, *dict, *debug;
2283 mod = PyModule_Create(&builtinsmodule);
2284 if (mod == NULL)
2285 return NULL;
2286 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002287
Tim Peters7571a0f2003-03-23 17:52:28 +00002288#ifdef Py_TRACE_REFS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002289 /* "builtins" exposes a number of statically allocated objects
2290 * that, before this code was added in 2.3, never showed up in
2291 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2292 * result, programs leaking references to None and False (etc)
2293 * couldn't be diagnosed by examining sys.getobjects(0).
2294 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002295#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2296#else
2297#define ADD_TO_ALL(OBJECT) (void)0
2298#endif
2299
Tim Peters4b7625e2001-09-13 21:37:17 +00002300#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002301 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2302 return NULL; \
2303 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002304
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002305 SETBUILTIN("None", Py_None);
2306 SETBUILTIN("Ellipsis", Py_Ellipsis);
2307 SETBUILTIN("NotImplemented", Py_NotImplemented);
2308 SETBUILTIN("False", Py_False);
2309 SETBUILTIN("True", Py_True);
2310 SETBUILTIN("bool", &PyBool_Type);
2311 SETBUILTIN("memoryview", &PyMemoryView_Type);
2312 SETBUILTIN("bytearray", &PyByteArray_Type);
2313 SETBUILTIN("bytes", &PyBytes_Type);
2314 SETBUILTIN("classmethod", &PyClassMethod_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002315#ifndef WITHOUT_COMPLEX
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002316 SETBUILTIN("complex", &PyComplex_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002317#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002318 SETBUILTIN("dict", &PyDict_Type);
2319 SETBUILTIN("enumerate", &PyEnum_Type);
2320 SETBUILTIN("filter", &PyFilter_Type);
2321 SETBUILTIN("float", &PyFloat_Type);
2322 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2323 SETBUILTIN("property", &PyProperty_Type);
2324 SETBUILTIN("int", &PyLong_Type);
2325 SETBUILTIN("list", &PyList_Type);
2326 SETBUILTIN("map", &PyMap_Type);
2327 SETBUILTIN("object", &PyBaseObject_Type);
2328 SETBUILTIN("range", &PyRange_Type);
2329 SETBUILTIN("reversed", &PyReversed_Type);
2330 SETBUILTIN("set", &PySet_Type);
2331 SETBUILTIN("slice", &PySlice_Type);
2332 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2333 SETBUILTIN("str", &PyUnicode_Type);
2334 SETBUILTIN("super", &PySuper_Type);
2335 SETBUILTIN("tuple", &PyTuple_Type);
2336 SETBUILTIN("type", &PyType_Type);
2337 SETBUILTIN("zip", &PyZip_Type);
2338 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2339 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2340 Py_XDECREF(debug);
2341 return NULL;
2342 }
2343 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002344
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002345 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002346#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002347#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002348}