blob: 97f7b961264665aca7efacdb1c49a2b4cd942b78 [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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000218 PyObject *it, *item;
219 PyObject *(*iternext)(PyObject *);
220 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000260 PyObject *it, *item;
261 PyObject *(*iternext)(PyObject *);
262 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000335 PyObject *func, *seq;
336 PyObject *it;
337 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
340 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
343 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 /* Get iterator. */
346 it = PyObject_GetIter(seq);
347 if (it == NULL)
348 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000360 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000361}
362
363static void
364filter_dealloc(filterobject *lz)
365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000383 PyObject *item;
384 PyObject *it = lz->it;
385 long ok;
386 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000485 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 if (!PyArg_ParseTuple(args, "i:chr", &x))
488 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000509 char *str;
510 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000556 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000567 if (!dont_inherit) {
568 PyEval_MergeCompilerFlags(&cf);
569 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000634 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000658 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000726 while (*str == ' ' || *str == '\t')
727 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000752 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
753 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Dickinson480e8e32009-12-19 21:19:35 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000828 PyObject *v, *result, *dflt = NULL;
829 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000861 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000877 PyObject *v;
878 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000933 PyObject *it, *iters, *func;
934 mapobject *lz;
935 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
938 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000947 iters = PyTuple_New(numargs-1);
948 if (iters == NULL)
949 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000972 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000973}
974
975static void
976map_dealloc(mapobject *lz)
977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000995 PyObject *val;
996 PyObject *argtuple;
997 PyObject *result;
998 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +00001071 PyObject *it, *res;
1072 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +00001112 PyObject *v;
1113 PyObject *name;
1114 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +00001134 PyObject *v;
1135 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +00001155 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +00001185 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +00001211 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +00001228 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +00001319 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001320Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001322Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +00001373 long ord;
1374 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +00001441 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +00001478 if (sep == Py_None) {
1479 sep = NULL;
1480 }
1481 else if (sep && !PyUnicode_Check(sep)) {
1482 PyErr_Format(PyExc_TypeError,
1483 "sep must be None or a string, not %.200s",
1484 sep->ob_type->tp_name);
1485 return NULL;
1486 }
1487 if (end == Py_None) {
1488 end = NULL;
1489 }
1490 else if (end && !PyUnicode_Check(end)) {
1491 PyErr_Format(PyExc_TypeError,
1492 "end must be None or a string, not %.200s",
1493 end->ob_type->tp_name);
1494 return NULL;
1495 }
Guido van Rossum34343512006-11-30 22:13:52 +00001496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 for (i = 0; i < PyTuple_Size(args); i++) {
1498 if (i > 0) {
1499 if (sep == NULL)
1500 err = PyFile_WriteString(" ", file);
1501 else
1502 err = PyFile_WriteObject(sep, file,
1503 Py_PRINT_RAW);
1504 if (err)
1505 return NULL;
1506 }
1507 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1508 Py_PRINT_RAW);
1509 if (err)
1510 return NULL;
1511 }
Guido van Rossum34343512006-11-30 22:13:52 +00001512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 if (end == NULL)
1514 err = PyFile_WriteString("\n", file);
1515 else
1516 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1517 if (err)
1518 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001521}
1522
1523PyDoc_STRVAR(print_doc,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001524"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001525\n\
1526Prints the values to a stream, or to sys.stdout by default.\n\
1527Optional keyword arguments:\n\
1528file: a file-like object (stream); defaults to the current sys.stdout.\n\
1529sep: string inserted between values, default a space.\n\
1530end: string appended after the last value, default a newline.");
1531
1532
Guido van Rossuma88a0332007-02-26 16:59:55 +00001533static PyObject *
1534builtin_input(PyObject *self, PyObject *args)
1535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 PyObject *promptarg = NULL;
1537 PyObject *fin = PySys_GetObject("stdin");
1538 PyObject *fout = PySys_GetObject("stdout");
1539 PyObject *ferr = PySys_GetObject("stderr");
1540 PyObject *tmp;
1541 long fd;
1542 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 /* Parse arguments */
1545 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1546 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 /* Check that stdin/out/err are intact */
1549 if (fin == NULL || fin == Py_None) {
1550 PyErr_SetString(PyExc_RuntimeError,
1551 "input(): lost sys.stdin");
1552 return NULL;
1553 }
1554 if (fout == NULL || fout == Py_None) {
1555 PyErr_SetString(PyExc_RuntimeError,
1556 "input(): lost sys.stdout");
1557 return NULL;
1558 }
1559 if (ferr == NULL || ferr == Py_None) {
1560 PyErr_SetString(PyExc_RuntimeError,
1561 "input(): lost sys.stderr");
1562 return NULL;
1563 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 /* First of all, flush stderr */
1566 tmp = PyObject_CallMethod(ferr, "flush", "");
1567 if (tmp == NULL)
1568 PyErr_Clear();
1569 else
1570 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 /* We should only use (GNU) readline if Python's sys.stdin and
1573 sys.stdout are the same as C's stdin and stdout, because we
1574 need to pass it those. */
1575 tmp = PyObject_CallMethod(fin, "fileno", "");
1576 if (tmp == NULL) {
1577 PyErr_Clear();
1578 tty = 0;
1579 }
1580 else {
1581 fd = PyLong_AsLong(tmp);
1582 Py_DECREF(tmp);
1583 if (fd < 0 && PyErr_Occurred())
1584 return NULL;
1585 tty = fd == fileno(stdin) && isatty(fd);
1586 }
1587 if (tty) {
1588 tmp = PyObject_CallMethod(fout, "fileno", "");
1589 if (tmp == NULL)
1590 PyErr_Clear();
1591 else {
1592 fd = PyLong_AsLong(tmp);
1593 Py_DECREF(tmp);
1594 if (fd < 0 && PyErr_Occurred())
1595 return NULL;
1596 tty = fd == fileno(stdout) && isatty(fd);
1597 }
1598 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 /* If we're interactive, use (GNU) readline */
1601 if (tty) {
1602 PyObject *po;
1603 char *prompt;
1604 char *s;
1605 PyObject *stdin_encoding;
1606 PyObject *result;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1609 if (!stdin_encoding)
1610 /* stdin is a text stream, so it must have an
1611 encoding. */
1612 return NULL;
1613 tmp = PyObject_CallMethod(fout, "flush", "");
1614 if (tmp == NULL)
1615 PyErr_Clear();
1616 else
1617 Py_DECREF(tmp);
1618 if (promptarg != NULL) {
1619 PyObject *stringpo;
1620 PyObject *stdout_encoding;
1621 stdout_encoding = PyObject_GetAttrString(fout,
1622 "encoding");
1623 if (stdout_encoding == NULL) {
1624 Py_DECREF(stdin_encoding);
1625 return NULL;
1626 }
1627 stringpo = PyObject_Str(promptarg);
1628 if (stringpo == NULL) {
1629 Py_DECREF(stdin_encoding);
1630 Py_DECREF(stdout_encoding);
1631 return NULL;
1632 }
1633 po = PyUnicode_AsEncodedString(stringpo,
1634 _PyUnicode_AsString(stdout_encoding), NULL);
1635 Py_DECREF(stdout_encoding);
1636 Py_DECREF(stringpo);
1637 if (po == NULL) {
1638 Py_DECREF(stdin_encoding);
1639 return NULL;
1640 }
1641 prompt = PyBytes_AsString(po);
1642 if (prompt == NULL) {
1643 Py_DECREF(stdin_encoding);
1644 Py_DECREF(po);
1645 return NULL;
1646 }
1647 }
1648 else {
1649 po = NULL;
1650 prompt = "";
1651 }
1652 s = PyOS_Readline(stdin, stdout, prompt);
1653 Py_XDECREF(po);
1654 if (s == NULL) {
1655 if (!PyErr_Occurred())
1656 PyErr_SetNone(PyExc_KeyboardInterrupt);
1657 Py_DECREF(stdin_encoding);
1658 return NULL;
1659 }
1660 if (*s == '\0') {
1661 PyErr_SetNone(PyExc_EOFError);
1662 result = NULL;
1663 }
1664 else { /* strip trailing '\n' */
1665 size_t len = strlen(s);
1666 if (len > PY_SSIZE_T_MAX) {
1667 PyErr_SetString(PyExc_OverflowError,
1668 "input: input too long");
1669 result = NULL;
1670 }
1671 else {
1672 result = PyUnicode_Decode
1673 (s, len-1,
1674 _PyUnicode_AsString(stdin_encoding),
1675 NULL);
1676 }
1677 }
1678 Py_DECREF(stdin_encoding);
1679 PyMem_FREE(s);
1680 return result;
1681 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 /* Fallback if we're not interactive */
1684 if (promptarg != NULL) {
1685 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1686 return NULL;
1687 }
1688 tmp = PyObject_CallMethod(fout, "flush", "");
1689 if (tmp == NULL)
1690 PyErr_Clear();
1691 else
1692 Py_DECREF(tmp);
1693 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001694}
1695
1696PyDoc_STRVAR(input_doc,
1697"input([prompt]) -> string\n\
1698\n\
1699Read a string from standard input. The trailing newline is stripped.\n\
1700If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1701On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1702is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001703
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001704
Guido van Rossum79f25d91997-04-29 20:08:16 +00001705static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001706builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001709}
1710
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001711PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001712"repr(object) -> string\n\
1713\n\
1714Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001715For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001716
1717
Guido van Rossum79f25d91997-04-29 20:08:16 +00001718static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001719builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 static PyObject *round_str = NULL;
1722 PyObject *ndigits = NULL;
1723 static char *kwlist[] = {"number", "ndigits", 0};
1724 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1727 kwlist, &number, &ndigits))
1728 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 if (Py_TYPE(number)->tp_dict == NULL) {
1731 if (PyType_Ready(Py_TYPE(number)) < 0)
1732 return NULL;
1733 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 if (round_str == NULL) {
1736 round_str = PyUnicode_InternFromString("__round__");
1737 if (round_str == NULL)
1738 return NULL;
1739 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 round = _PyType_Lookup(Py_TYPE(number), round_str);
1742 if (round == NULL) {
1743 PyErr_Format(PyExc_TypeError,
1744 "type %.100s doesn't define __round__ method",
1745 Py_TYPE(number)->tp_name);
1746 return NULL;
1747 }
Alex Martelliae211f92007-08-22 23:21:33 +00001748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 if (ndigits == NULL)
1750 return PyObject_CallFunction(round, "O", number);
1751 else
1752 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001753}
1754
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001755PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001756"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001757\n\
1758Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001759This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001760same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001761
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001762
Raymond Hettinger64958a12003-12-17 20:43:33 +00001763static PyObject *
1764builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1767 PyObject *callable;
1768 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1769 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 /* args 1-3 should match listsort in Objects/listobject.c */
1772 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1773 kwlist, &seq, &keyfunc, &reverse))
1774 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 newlist = PySequence_List(seq);
1777 if (newlist == NULL)
1778 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 callable = PyObject_GetAttrString(newlist, "sort");
1781 if (callable == NULL) {
1782 Py_DECREF(newlist);
1783 return NULL;
1784 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 newargs = PyTuple_GetSlice(args, 1, 4);
1787 if (newargs == NULL) {
1788 Py_DECREF(newlist);
1789 Py_DECREF(callable);
1790 return NULL;
1791 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 v = PyObject_Call(callable, newargs, kwds);
1794 Py_DECREF(newargs);
1795 Py_DECREF(callable);
1796 if (v == NULL) {
1797 Py_DECREF(newlist);
1798 return NULL;
1799 }
1800 Py_DECREF(v);
1801 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001802}
1803
1804PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001805"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001806
Guido van Rossum79f25d91997-04-29 20:08:16 +00001807static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001808builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 PyObject *v = NULL;
1811 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1814 return NULL;
1815 if (v == NULL) {
1816 d = PyEval_GetLocals();
1817 if (d == NULL) {
1818 if (!PyErr_Occurred())
1819 PyErr_SetString(PyExc_SystemError,
1820 "vars(): no locals!?");
1821 }
1822 else
1823 Py_INCREF(d);
1824 }
1825 else {
1826 d = PyObject_GetAttrString(v, "__dict__");
1827 if (d == NULL) {
1828 PyErr_SetString(PyExc_TypeError,
1829 "vars() argument must have __dict__ attribute");
1830 return NULL;
1831 }
1832 }
1833 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001834}
1835
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001836PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001837"vars([object]) -> dictionary\n\
1838\n\
1839Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001840With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001841
Alex Martellia70b1912003-04-22 08:12:33 +00001842static PyObject*
1843builtin_sum(PyObject *self, PyObject *args)
1844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 PyObject *seq;
1846 PyObject *result = NULL;
1847 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1850 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 iter = PyObject_GetIter(seq);
1853 if (iter == NULL)
1854 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 if (result == NULL) {
1857 result = PyLong_FromLong(0);
1858 if (result == NULL) {
1859 Py_DECREF(iter);
1860 return NULL;
1861 }
1862 } else {
1863 /* reject string values for 'start' parameter */
1864 if (PyUnicode_Check(result)) {
1865 PyErr_SetString(PyExc_TypeError,
1866 "sum() can't sum strings [use ''.join(seq) instead]");
1867 Py_DECREF(iter);
1868 return NULL;
1869 }
1870 if (PyByteArray_Check(result)) {
1871 PyErr_SetString(PyExc_TypeError,
1872 "sum() can't sum bytes [use b''.join(seq) instead]");
1873 Py_DECREF(iter);
1874 return NULL;
1875 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 Py_INCREF(result);
1878 }
Alex Martellia70b1912003-04-22 08:12:33 +00001879
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001880#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1882 Assumes all inputs are the same type. If the assumption fails, default
1883 to the more general routine.
1884 */
1885 if (PyLong_CheckExact(result)) {
1886 int overflow;
1887 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1888 /* If this already overflowed, don't even enter the loop. */
1889 if (overflow == 0) {
1890 Py_DECREF(result);
1891 result = NULL;
1892 }
1893 while(result == NULL) {
1894 item = PyIter_Next(iter);
1895 if (item == NULL) {
1896 Py_DECREF(iter);
1897 if (PyErr_Occurred())
1898 return NULL;
1899 return PyLong_FromLong(i_result);
1900 }
1901 if (PyLong_CheckExact(item)) {
1902 long b = PyLong_AsLongAndOverflow(item, &overflow);
1903 long x = i_result + b;
1904 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1905 i_result = x;
1906 Py_DECREF(item);
1907 continue;
1908 }
1909 }
1910 /* Either overflowed or is not an int. Restore real objects and process normally */
1911 result = PyLong_FromLong(i_result);
1912 temp = PyNumber_Add(result, item);
1913 Py_DECREF(result);
1914 Py_DECREF(item);
1915 result = temp;
1916 if (result == NULL) {
1917 Py_DECREF(iter);
1918 return NULL;
1919 }
1920 }
1921 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 if (PyFloat_CheckExact(result)) {
1924 double f_result = PyFloat_AS_DOUBLE(result);
1925 Py_DECREF(result);
1926 result = NULL;
1927 while(result == NULL) {
1928 item = PyIter_Next(iter);
1929 if (item == NULL) {
1930 Py_DECREF(iter);
1931 if (PyErr_Occurred())
1932 return NULL;
1933 return PyFloat_FromDouble(f_result);
1934 }
1935 if (PyFloat_CheckExact(item)) {
1936 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1937 f_result += PyFloat_AS_DOUBLE(item);
1938 PyFPE_END_PROTECT(f_result)
1939 Py_DECREF(item);
1940 continue;
1941 }
1942 if (PyLong_CheckExact(item)) {
1943 long value;
1944 int overflow;
1945 value = PyLong_AsLongAndOverflow(item, &overflow);
1946 if (!overflow) {
1947 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1948 f_result += (double)value;
1949 PyFPE_END_PROTECT(f_result)
1950 Py_DECREF(item);
1951 continue;
1952 }
1953 }
1954 result = PyFloat_FromDouble(f_result);
1955 temp = PyNumber_Add(result, item);
1956 Py_DECREF(result);
1957 Py_DECREF(item);
1958 result = temp;
1959 if (result == NULL) {
1960 Py_DECREF(iter);
1961 return NULL;
1962 }
1963 }
1964 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001965#endif
1966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 for(;;) {
1968 item = PyIter_Next(iter);
1969 if (item == NULL) {
1970 /* error, or end-of-sequence */
1971 if (PyErr_Occurred()) {
1972 Py_DECREF(result);
1973 result = NULL;
1974 }
1975 break;
1976 }
1977 /* It's tempting to use PyNumber_InPlaceAdd instead of
1978 PyNumber_Add here, to avoid quadratic running time
1979 when doing 'sum(list_of_lists, [])'. However, this
1980 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00001981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 empty = []
1983 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00001984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 would change the value of empty. */
1986 temp = PyNumber_Add(result, item);
1987 Py_DECREF(result);
1988 Py_DECREF(item);
1989 result = temp;
1990 if (result == NULL)
1991 break;
1992 }
1993 Py_DECREF(iter);
1994 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00001995}
1996
1997PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001998"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00001999\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002000Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2001of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002002empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002003
2004
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002005static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002006builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 PyObject *inst;
2009 PyObject *cls;
2010 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2013 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 retval = PyObject_IsInstance(inst, cls);
2016 if (retval < 0)
2017 return NULL;
2018 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002019}
2020
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002021PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002022"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002023\n\
2024Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002025With a type as second argument, return whether that is the object's type.\n\
2026The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002027isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002028
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002029
2030static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002031builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 PyObject *derived;
2034 PyObject *cls;
2035 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2038 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 retval = PyObject_IsSubclass(derived, cls);
2041 if (retval < 0)
2042 return NULL;
2043 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002044}
2045
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002046PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002047"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002048\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002049Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2050When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2051is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002052
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002053
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002054typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 PyObject_HEAD
2056 Py_ssize_t tuplesize;
2057 PyObject *ittuple; /* tuple of iterators */
2058 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002059} zipobject;
2060
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002061static PyObject *
2062zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 zipobject *lz;
2065 Py_ssize_t i;
2066 PyObject *ittuple; /* tuple of iterators */
2067 PyObject *result;
2068 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2071 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 /* args must be a tuple */
2074 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 /* obtain iterators */
2077 ittuple = PyTuple_New(tuplesize);
2078 if (ittuple == NULL)
2079 return NULL;
2080 for (i=0; i < tuplesize; ++i) {
2081 PyObject *item = PyTuple_GET_ITEM(args, i);
2082 PyObject *it = PyObject_GetIter(item);
2083 if (it == NULL) {
2084 if (PyErr_ExceptionMatches(PyExc_TypeError))
2085 PyErr_Format(PyExc_TypeError,
2086 "zip argument #%zd must support iteration",
2087 i+1);
2088 Py_DECREF(ittuple);
2089 return NULL;
2090 }
2091 PyTuple_SET_ITEM(ittuple, i, it);
2092 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 /* create a result holder */
2095 result = PyTuple_New(tuplesize);
2096 if (result == NULL) {
2097 Py_DECREF(ittuple);
2098 return NULL;
2099 }
2100 for (i=0 ; i < tuplesize ; i++) {
2101 Py_INCREF(Py_None);
2102 PyTuple_SET_ITEM(result, i, Py_None);
2103 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 /* create zipobject structure */
2106 lz = (zipobject *)type->tp_alloc(type, 0);
2107 if (lz == NULL) {
2108 Py_DECREF(ittuple);
2109 Py_DECREF(result);
2110 return NULL;
2111 }
2112 lz->ittuple = ittuple;
2113 lz->tuplesize = tuplesize;
2114 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002117}
2118
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002119static void
2120zip_dealloc(zipobject *lz)
2121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 PyObject_GC_UnTrack(lz);
2123 Py_XDECREF(lz->ittuple);
2124 Py_XDECREF(lz->result);
2125 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002126}
2127
2128static int
2129zip_traverse(zipobject *lz, visitproc visit, void *arg)
2130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 Py_VISIT(lz->ittuple);
2132 Py_VISIT(lz->result);
2133 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002134}
2135
2136static PyObject *
2137zip_next(zipobject *lz)
2138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 Py_ssize_t i;
2140 Py_ssize_t tuplesize = lz->tuplesize;
2141 PyObject *result = lz->result;
2142 PyObject *it;
2143 PyObject *item;
2144 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 if (tuplesize == 0)
2147 return NULL;
2148 if (Py_REFCNT(result) == 1) {
2149 Py_INCREF(result);
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 olditem = PyTuple_GET_ITEM(result, i);
2158 PyTuple_SET_ITEM(result, i, item);
2159 Py_DECREF(olditem);
2160 }
2161 } else {
2162 result = PyTuple_New(tuplesize);
2163 if (result == NULL)
2164 return NULL;
2165 for (i=0 ; i < tuplesize ; i++) {
2166 it = PyTuple_GET_ITEM(lz->ittuple, i);
2167 item = (*Py_TYPE(it)->tp_iternext)(it);
2168 if (item == NULL) {
2169 Py_DECREF(result);
2170 return NULL;
2171 }
2172 PyTuple_SET_ITEM(result, i, item);
2173 }
2174 }
2175 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002176}
Barry Warsawbd599b52000-08-03 15:45:29 +00002177
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002178PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002179"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002180\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002181Return a zip object whose .__next__() method returns a tuple where\n\
2182the i-th element comes from the i-th iterable argument. The .__next__()\n\
2183method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002184is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002185
2186PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2188 "zip", /* tp_name */
2189 sizeof(zipobject), /* tp_basicsize */
2190 0, /* tp_itemsize */
2191 /* methods */
2192 (destructor)zip_dealloc, /* tp_dealloc */
2193 0, /* tp_print */
2194 0, /* tp_getattr */
2195 0, /* tp_setattr */
2196 0, /* tp_reserved */
2197 0, /* tp_repr */
2198 0, /* tp_as_number */
2199 0, /* tp_as_sequence */
2200 0, /* tp_as_mapping */
2201 0, /* tp_hash */
2202 0, /* tp_call */
2203 0, /* tp_str */
2204 PyObject_GenericGetAttr, /* tp_getattro */
2205 0, /* tp_setattro */
2206 0, /* tp_as_buffer */
2207 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2208 Py_TPFLAGS_BASETYPE, /* tp_flags */
2209 zip_doc, /* tp_doc */
2210 (traverseproc)zip_traverse, /* tp_traverse */
2211 0, /* tp_clear */
2212 0, /* tp_richcompare */
2213 0, /* tp_weaklistoffset */
2214 PyObject_SelfIter, /* tp_iter */
2215 (iternextfunc)zip_next, /* tp_iternext */
2216 0, /* tp_methods */
2217 0, /* tp_members */
2218 0, /* tp_getset */
2219 0, /* tp_base */
2220 0, /* tp_dict */
2221 0, /* tp_descr_get */
2222 0, /* tp_descr_set */
2223 0, /* tp_dictoffset */
2224 0, /* tp_init */
2225 PyType_GenericAlloc, /* tp_alloc */
2226 zip_new, /* tp_new */
2227 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002228};
Barry Warsawbd599b52000-08-03 15:45:29 +00002229
2230
Guido van Rossum79f25d91997-04-29 20:08:16 +00002231static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 {"__build_class__", (PyCFunction)builtin___build_class__,
2233 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2234 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2235 {"abs", builtin_abs, METH_O, abs_doc},
2236 {"all", builtin_all, METH_O, all_doc},
2237 {"any", builtin_any, METH_O, any_doc},
2238 {"ascii", builtin_ascii, METH_O, ascii_doc},
2239 {"bin", builtin_bin, METH_O, bin_doc},
2240 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2241 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2242 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2243 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2244 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2245 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2246 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2247 {"format", builtin_format, METH_VARARGS, format_doc},
2248 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2249 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2250 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2251 {"hash", builtin_hash, METH_O, hash_doc},
2252 {"hex", builtin_hex, METH_O, hex_doc},
2253 {"id", builtin_id, METH_O, id_doc},
2254 {"input", builtin_input, METH_VARARGS, input_doc},
2255 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2256 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2257 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2258 {"len", builtin_len, METH_O, len_doc},
2259 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2260 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2261 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2262 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2263 {"oct", builtin_oct, METH_O, oct_doc},
2264 {"ord", builtin_ord, METH_O, ord_doc},
2265 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2266 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2267 {"repr", builtin_repr, METH_O, repr_doc},
2268 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2269 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2270 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2271 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2272 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2273 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002274};
2275
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002276PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002277"Built-in functions, exceptions, and other objects.\n\
2278\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002279Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002280
Martin v. Löwis1a214512008-06-11 05:26:20 +00002281static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 PyModuleDef_HEAD_INIT,
2283 "builtins",
2284 builtin_doc,
2285 -1, /* multiple "initialization" just copies the module dict. */
2286 builtin_methods,
2287 NULL,
2288 NULL,
2289 NULL,
2290 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002291};
2292
2293
Guido van Rossum25ce5661997-08-02 03:10:38 +00002294PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002295_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 PyObject *mod, *dict, *debug;
2298 mod = PyModule_Create(&builtinsmodule);
2299 if (mod == NULL)
2300 return NULL;
2301 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002302
Tim Peters7571a0f2003-03-23 17:52:28 +00002303#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 /* "builtins" exposes a number of statically allocated objects
2305 * that, before this code was added in 2.3, never showed up in
2306 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2307 * result, programs leaking references to None and False (etc)
2308 * couldn't be diagnosed by examining sys.getobjects(0).
2309 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002310#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2311#else
2312#define ADD_TO_ALL(OBJECT) (void)0
2313#endif
2314
Tim Peters4b7625e2001-09-13 21:37:17 +00002315#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2317 return NULL; \
2318 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 SETBUILTIN("None", Py_None);
2321 SETBUILTIN("Ellipsis", Py_Ellipsis);
2322 SETBUILTIN("NotImplemented", Py_NotImplemented);
2323 SETBUILTIN("False", Py_False);
2324 SETBUILTIN("True", Py_True);
2325 SETBUILTIN("bool", &PyBool_Type);
2326 SETBUILTIN("memoryview", &PyMemoryView_Type);
2327 SETBUILTIN("bytearray", &PyByteArray_Type);
2328 SETBUILTIN("bytes", &PyBytes_Type);
2329 SETBUILTIN("classmethod", &PyClassMethod_Type);
2330 SETBUILTIN("complex", &PyComplex_Type);
2331 SETBUILTIN("dict", &PyDict_Type);
2332 SETBUILTIN("enumerate", &PyEnum_Type);
2333 SETBUILTIN("filter", &PyFilter_Type);
2334 SETBUILTIN("float", &PyFloat_Type);
2335 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2336 SETBUILTIN("property", &PyProperty_Type);
2337 SETBUILTIN("int", &PyLong_Type);
2338 SETBUILTIN("list", &PyList_Type);
2339 SETBUILTIN("map", &PyMap_Type);
2340 SETBUILTIN("object", &PyBaseObject_Type);
2341 SETBUILTIN("range", &PyRange_Type);
2342 SETBUILTIN("reversed", &PyReversed_Type);
2343 SETBUILTIN("set", &PySet_Type);
2344 SETBUILTIN("slice", &PySlice_Type);
2345 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2346 SETBUILTIN("str", &PyUnicode_Type);
2347 SETBUILTIN("super", &PySuper_Type);
2348 SETBUILTIN("tuple", &PyTuple_Type);
2349 SETBUILTIN("type", &PyType_Type);
2350 SETBUILTIN("zip", &PyZip_Type);
2351 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2352 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2353 Py_XDECREF(debug);
2354 return NULL;
2355 }
2356 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002359#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002360#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002361}