blob: 60bceb758165dae3e85ba419837ab425091565d7 [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum5b722181993-03-30 17:46:03 +00008#include "eval.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00009
Guido van Rossum6bf62da1997-04-11 20:37:35 +000010#include <ctype.h>
11
Victor Stinnerb744ba12010-05-15 12:27:16 +000012#ifdef HAVE_LANGINFO_H
13#include <langinfo.h> /* CODESET */
14#endif
15
Mark Hammond26cffde42001-05-14 12:17:34 +000016/* The default encoding used by the platform file system APIs
17 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000018
19 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
20 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000021*/
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000022#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Mark Hammond26cffde42001-05-14 12:17:34 +000023const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000024int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000025#elif defined(__APPLE__)
26const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000027int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerb744ba12010-05-15 12:27:16 +000028#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
29const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000030int Py_HasFileSystemDefaultEncoding = 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +000031#else
32const char *Py_FileSystemDefaultEncoding = "utf-8";
33int Py_HasFileSystemDefaultEncoding = 1;
Mark Hammond26cffde42001-05-14 12:17:34 +000034#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000035
Guido van Rossum79f25d91997-04-29 20:08:16 +000036static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000037builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
38{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell;
40 PyObject *cls = NULL;
41 Py_ssize_t nargs, nbases;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043 assert(args != NULL);
44 if (!PyTuple_Check(args)) {
45 PyErr_SetString(PyExc_TypeError,
46 "__build_class__: args is not a tuple");
47 return NULL;
48 }
49 nargs = PyTuple_GET_SIZE(args);
50 if (nargs < 2) {
51 PyErr_SetString(PyExc_TypeError,
52 "__build_class__: not enough arguments");
53 return NULL;
54 }
55 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
56 name = PyTuple_GET_ITEM(args, 1);
57 if (!PyUnicode_Check(name)) {
58 PyErr_SetString(PyExc_TypeError,
59 "__build_class__: name is not a string");
60 return NULL;
61 }
62 bases = PyTuple_GetSlice(args, 2, nargs);
63 if (bases == NULL)
64 return NULL;
65 nbases = nargs - 2;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 if (kwds == NULL) {
68 meta = NULL;
69 mkw = NULL;
70 }
71 else {
72 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
73 if (mkw == NULL) {
74 Py_DECREF(bases);
75 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000076 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 meta = PyDict_GetItemString(mkw, "metaclass");
78 if (meta != NULL) {
79 Py_INCREF(meta);
80 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
81 Py_DECREF(meta);
82 Py_DECREF(mkw);
83 Py_DECREF(bases);
84 return NULL;
85 }
86 }
87 }
88 if (meta == NULL) {
89 if (PyTuple_GET_SIZE(bases) == 0)
90 meta = (PyObject *) (&PyType_Type);
91 else {
92 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
93 meta = (PyObject *) (base0->ob_type);
94 }
95 Py_INCREF(meta);
96 }
97 prep = PyObject_GetAttrString(meta, "__prepare__");
98 if (prep == NULL) {
99 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
100 PyErr_Clear();
101 ns = PyDict_New();
102 }
103 else {
104 Py_DECREF(meta);
105 Py_XDECREF(mkw);
106 Py_DECREF(bases);
107 return NULL;
108 }
109 }
110 else {
111 PyObject *pargs = PyTuple_Pack(2, name, bases);
112 if (pargs == NULL) {
113 Py_DECREF(prep);
114 Py_DECREF(meta);
115 Py_XDECREF(mkw);
116 Py_DECREF(bases);
117 return NULL;
118 }
119 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
120 Py_DECREF(pargs);
121 Py_DECREF(prep);
122 }
123 if (ns == NULL) {
124 Py_DECREF(meta);
125 Py_XDECREF(mkw);
126 Py_DECREF(bases);
127 return NULL;
128 }
129 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
130 if (cell != NULL) {
131 PyObject *margs;
132 margs = PyTuple_Pack(3, name, bases, ns);
133 if (margs != NULL) {
134 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
135 Py_DECREF(margs);
136 }
137 if (cls != NULL && PyCell_Check(cell)) {
138 Py_INCREF(cls);
139 PyCell_SET(cell, cls);
140 }
141 Py_DECREF(cell);
142 }
143 Py_DECREF(ns);
144 Py_DECREF(meta);
145 Py_XDECREF(mkw);
146 Py_DECREF(bases);
147 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000148}
149
150PyDoc_STRVAR(build_class_doc,
151"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
152\n\
153Internal helper function used by the class statement.");
154
155static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000156builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
159 "level", 0};
160 char *name;
161 PyObject *globals = NULL;
162 PyObject *locals = NULL;
163 PyObject *fromlist = NULL;
164 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
167 kwlist, &name, &globals, &locals, &fromlist, &level))
168 return NULL;
169 return PyImport_ImportModuleLevel(name, globals, locals,
170 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000171}
172
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000173PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000174"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000175\n\
176Import a module. The globals are only used to determine the context;\n\
177they are not modified. The locals are currently unused. The fromlist\n\
178should be a list of names to emulate ``from name import ...'', or an\n\
179empty list to emulate ``import name''.\n\
180When importing a module from a package, note that __import__('A.B', ...)\n\
181returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000182fromlist is not empty. Level is used to determine whether to perform \n\
183absolute or relative imports. -1 is the original strategy of attempting\n\
184both absolute and relative imports, 0 is absolute, a positive number\n\
185is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000186
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000187
Guido van Rossum79f25d91997-04-29 20:08:16 +0000188static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000189builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000192}
193
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000194PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000195"abs(number) -> number\n\
196\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000197Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000198
Raymond Hettinger96229b12005-03-11 06:49:40 +0000199static PyObject *
200builtin_all(PyObject *self, PyObject *v)
201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 PyObject *it, *item;
203 PyObject *(*iternext)(PyObject *);
204 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 it = PyObject_GetIter(v);
207 if (it == NULL)
208 return NULL;
209 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 for (;;) {
212 item = iternext(it);
213 if (item == NULL)
214 break;
215 cmp = PyObject_IsTrue(item);
216 Py_DECREF(item);
217 if (cmp < 0) {
218 Py_DECREF(it);
219 return NULL;
220 }
221 if (cmp == 0) {
222 Py_DECREF(it);
223 Py_RETURN_FALSE;
224 }
225 }
226 Py_DECREF(it);
227 if (PyErr_Occurred()) {
228 if (PyErr_ExceptionMatches(PyExc_StopIteration))
229 PyErr_Clear();
230 else
231 return NULL;
232 }
233 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000234}
235
236PyDoc_STRVAR(all_doc,
237"all(iterable) -> bool\n\
238\n\
239Return True if bool(x) is True for all values x in the iterable.");
240
241static PyObject *
242builtin_any(PyObject *self, PyObject *v)
243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 PyObject *it, *item;
245 PyObject *(*iternext)(PyObject *);
246 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 it = PyObject_GetIter(v);
249 if (it == NULL)
250 return NULL;
251 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 for (;;) {
254 item = iternext(it);
255 if (item == NULL)
256 break;
257 cmp = PyObject_IsTrue(item);
258 Py_DECREF(item);
259 if (cmp < 0) {
260 Py_DECREF(it);
261 return NULL;
262 }
263 if (cmp == 1) {
264 Py_DECREF(it);
265 Py_RETURN_TRUE;
266 }
267 }
268 Py_DECREF(it);
269 if (PyErr_Occurred()) {
270 if (PyErr_ExceptionMatches(PyExc_StopIteration))
271 PyErr_Clear();
272 else
273 return NULL;
274 }
275 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000276}
277
278PyDoc_STRVAR(any_doc,
279"any(iterable) -> bool\n\
280\n\
281Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000282
Georg Brandl559e5d72008-06-11 18:37:52 +0000283static PyObject *
284builtin_ascii(PyObject *self, PyObject *v)
285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000287}
288
289PyDoc_STRVAR(ascii_doc,
290"ascii(object) -> string\n\
291\n\
292As repr(), return a string containing a printable representation of an\n\
293object, but escape the non-ASCII characters in the string returned by\n\
294repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
295to that returned by repr() in Python 2.");
296
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000297
Guido van Rossum79f25d91997-04-29 20:08:16 +0000298static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000299builtin_bin(PyObject *self, PyObject *v)
300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000302}
303
304PyDoc_STRVAR(bin_doc,
305"bin(number) -> string\n\
306\n\
307Return the binary representation of an integer or long integer.");
308
309
Raymond Hettinger17301e92008-03-13 00:19:26 +0000310typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 PyObject_HEAD
312 PyObject *func;
313 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000314} filterobject;
315
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000316static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000317filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 PyObject *func, *seq;
320 PyObject *it;
321 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
324 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
327 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 /* Get iterator. */
330 it = PyObject_GetIter(seq);
331 if (it == NULL)
332 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 /* create filterobject structure */
335 lz = (filterobject *)type->tp_alloc(type, 0);
336 if (lz == NULL) {
337 Py_DECREF(it);
338 return NULL;
339 }
340 Py_INCREF(func);
341 lz->func = func;
342 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000345}
346
347static void
348filter_dealloc(filterobject *lz)
349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 PyObject_GC_UnTrack(lz);
351 Py_XDECREF(lz->func);
352 Py_XDECREF(lz->it);
353 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000354}
355
356static int
357filter_traverse(filterobject *lz, visitproc visit, void *arg)
358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 Py_VISIT(lz->it);
360 Py_VISIT(lz->func);
361 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000362}
363
364static PyObject *
365filter_next(filterobject *lz)
366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 PyObject *item;
368 PyObject *it = lz->it;
369 long ok;
370 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 iternext = *Py_TYPE(it)->tp_iternext;
373 for (;;) {
374 item = iternext(it);
375 if (item == NULL)
376 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
379 ok = PyObject_IsTrue(item);
380 } else {
381 PyObject *good;
382 good = PyObject_CallFunctionObjArgs(lz->func,
383 item, NULL);
384 if (good == NULL) {
385 Py_DECREF(item);
386 return NULL;
387 }
388 ok = PyObject_IsTrue(good);
389 Py_DECREF(good);
390 }
391 if (ok)
392 return item;
393 Py_DECREF(item);
394 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000395}
396
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000397PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000398"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000399\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000400Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000401is true. If function is None, return the items that are true.");
402
403PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 PyVarObject_HEAD_INIT(&PyType_Type, 0)
405 "filter", /* tp_name */
406 sizeof(filterobject), /* tp_basicsize */
407 0, /* tp_itemsize */
408 /* methods */
409 (destructor)filter_dealloc, /* tp_dealloc */
410 0, /* tp_print */
411 0, /* tp_getattr */
412 0, /* tp_setattr */
413 0, /* tp_reserved */
414 0, /* tp_repr */
415 0, /* tp_as_number */
416 0, /* tp_as_sequence */
417 0, /* tp_as_mapping */
418 0, /* tp_hash */
419 0, /* tp_call */
420 0, /* tp_str */
421 PyObject_GenericGetAttr, /* tp_getattro */
422 0, /* tp_setattro */
423 0, /* tp_as_buffer */
424 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
425 Py_TPFLAGS_BASETYPE, /* tp_flags */
426 filter_doc, /* tp_doc */
427 (traverseproc)filter_traverse, /* tp_traverse */
428 0, /* tp_clear */
429 0, /* tp_richcompare */
430 0, /* tp_weaklistoffset */
431 PyObject_SelfIter, /* tp_iter */
432 (iternextfunc)filter_next, /* tp_iternext */
433 0, /* tp_methods */
434 0, /* tp_members */
435 0, /* tp_getset */
436 0, /* tp_base */
437 0, /* tp_dict */
438 0, /* tp_descr_get */
439 0, /* tp_descr_set */
440 0, /* tp_dictoffset */
441 0, /* tp_init */
442 PyType_GenericAlloc, /* tp_alloc */
443 filter_new, /* tp_new */
444 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000445};
446
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000447
Eric Smith8c663262007-08-25 02:26:07 +0000448static PyObject *
449builtin_format(PyObject *self, PyObject *args)
450{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000451 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000452 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000453
Eric Smith8fd3eba2008-02-17 19:48:00 +0000454 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000456
Eric Smith8fd3eba2008-02-17 19:48:00 +0000457 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000458}
459
Eric Smith8c663262007-08-25 02:26:07 +0000460PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000461"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000462\n\
Eric Smith81936692007-08-31 01:14:01 +0000463Returns value.__format__(format_spec)\n\
464format_spec defaults to \"\"");
465
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000466static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000467builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (!PyArg_ParseTuple(args, "i:chr", &x))
472 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000475}
476
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000477PyDoc_VAR(chr_doc) = PyDoc_STR(
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000478"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000479\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000480Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000481)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000482#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000483PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000484"\nIf 0x10000 <= i, a surrogate pair is returned."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000485)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000486#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000487;
Guido van Rossum09095f32000-03-10 23:00:52 +0000488
489
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000490static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000491source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 char *str;
494 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 if (PyUnicode_Check(cmd)) {
497 cf->cf_flags |= PyCF_IGNORE_COOKIE;
498 cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL);
499 if (cmd == NULL)
500 return NULL;
501 }
502 else if (!PyObject_CheckReadBuffer(cmd)) {
503 PyErr_Format(PyExc_TypeError,
504 "%s() arg 1 must be a %s object",
505 funcname, what);
506 return NULL;
507 }
508 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
509 return NULL;
510 }
511 if (strlen(str) != size) {
512 PyErr_SetString(PyExc_TypeError,
513 "source code string cannot contain null bytes");
514 return NULL;
515 }
516 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000517}
518
Guido van Rossum79f25d91997-04-29 20:08:16 +0000519static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000520builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 char *str;
523 char *filename;
524 char *startstr;
525 int mode = -1;
526 int dont_inherit = 0;
527 int supplied_flags = 0;
528 int is_ast;
529 PyCompilerFlags cf;
530 PyObject *cmd;
531 static char *kwlist[] = {"source", "filename", "mode", "flags",
532 "dont_inherit", NULL};
533 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
536 kwlist, &cmd, &filename, &startstr,
537 &supplied_flags, &dont_inherit))
538 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 if (supplied_flags &
543 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
544 {
545 PyErr_SetString(PyExc_ValueError,
546 "compile(): unrecognised flags");
547 return NULL;
548 }
549 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 if (!dont_inherit) {
552 PyEval_MergeCompilerFlags(&cf);
553 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 if (strcmp(startstr, "exec") == 0)
556 mode = 0;
557 else if (strcmp(startstr, "eval") == 0)
558 mode = 1;
559 else if (strcmp(startstr, "single") == 0)
560 mode = 2;
561 else {
562 PyErr_SetString(PyExc_ValueError,
563 "compile() arg 3 must be 'exec', 'eval' or 'single'");
564 return NULL;
565 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 is_ast = PyAST_Check(cmd);
568 if (is_ast == -1)
569 return NULL;
570 if (is_ast) {
571 PyObject *result;
572 if (supplied_flags & PyCF_ONLY_AST) {
573 Py_INCREF(cmd);
574 result = cmd;
575 }
576 else {
577 PyArena *arena;
578 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 arena = PyArena_New();
581 mod = PyAST_obj2mod(cmd, arena, mode);
582 if (mod == NULL) {
583 PyArena_Free(arena);
584 return NULL;
585 }
586 result = (PyObject*)PyAST_Compile(mod, filename,
587 &cf, arena);
588 PyArena_Free(arena);
589 }
590 return result;
591 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
594 if (str == NULL)
595 return NULL;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 return Py_CompileStringFlags(str, filename, start[mode], &cf);
Guido van Rossum5b722181993-03-30 17:46:03 +0000598}
599
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000600PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000601"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000602\n\
603Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000604into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000605The filename will be used for run-time error messages.\n\
606The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000607single (interactive) statement, or 'eval' to compile an expression.\n\
608The flags argument, if present, controls which future statements influence\n\
609the compilation of the code.\n\
610The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
611the effects of any future statements in effect in the code calling\n\
612compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000613in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000614
Guido van Rossum79f25d91997-04-29 20:08:16 +0000615static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000616builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
621 return NULL;
622 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000623}
624
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000625PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000626"dir([object]) -> list of strings\n"
627"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000628"If called without an argument, return the names in the current scope.\n"
629"Else, return an alphabetized list of names comprising (some of) the attributes\n"
630"of the given object, and of attributes reachable from it.\n"
631"If the object supplies a method named __dir__, it will be used; otherwise\n"
632"the default dir() logic is used and returns:\n"
633" for a module object: the module's attributes.\n"
634" for a class object: its attributes, and recursively the attributes\n"
635" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000636" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000637" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000638
Guido van Rossum79f25d91997-04-29 20:08:16 +0000639static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000640builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
645 return NULL;
646 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000647}
648
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000649PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000650"divmod(x, y) -> (div, mod)\n\
651\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000652Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000653
654
Guido van Rossum79f25d91997-04-29 20:08:16 +0000655static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000656builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 PyObject *cmd, *result, *tmp = NULL;
659 PyObject *globals = Py_None, *locals = Py_None;
660 char *str;
661 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
664 return NULL;
665 if (locals != Py_None && !PyMapping_Check(locals)) {
666 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
667 return NULL;
668 }
669 if (globals != Py_None && !PyDict_Check(globals)) {
670 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
671 "globals must be a real dict; try eval(expr, {}, mapping)"
672 : "globals must be a dict");
673 return NULL;
674 }
675 if (globals == Py_None) {
676 globals = PyEval_GetGlobals();
677 if (locals == Py_None)
678 locals = PyEval_GetLocals();
679 }
680 else if (locals == Py_None)
681 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 if (globals == NULL || locals == NULL) {
684 PyErr_SetString(PyExc_TypeError,
685 "eval must be given globals and locals "
686 "when called without a frame");
687 return NULL;
688 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
691 if (PyDict_SetItemString(globals, "__builtins__",
692 PyEval_GetBuiltins()) != 0)
693 return NULL;
694 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 if (PyCode_Check(cmd)) {
697 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
698 PyErr_SetString(PyExc_TypeError,
699 "code object passed to eval() may not contain free variables");
700 return NULL;
701 }
702 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
703 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
706 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
707 if (str == NULL)
708 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 while (*str == ' ' || *str == '\t')
711 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 (void)PyEval_MergeCompilerFlags(&cf);
714 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
715 Py_XDECREF(tmp);
716 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000717}
718
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000719PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000720"eval(source[, globals[, locals]]) -> value\n\
721\n\
722Evaluate the source in the context of globals and locals.\n\
723The source may be a string representing a Python expression\n\
724or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000725The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000726defaulting to the current globals and locals.\n\
727If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000728
Georg Brandl7cae87c2006-09-06 06:51:57 +0000729static PyObject *
730builtin_exec(PyObject *self, PyObject *args)
731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 PyObject *v;
733 PyObject *prog, *globals = Py_None, *locals = Py_None;
734 int plain = 0;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
737 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 if (globals == Py_None) {
740 globals = PyEval_GetGlobals();
741 if (locals == Py_None) {
742 locals = PyEval_GetLocals();
743 plain = 1;
744 }
745 if (!globals || !locals) {
746 PyErr_SetString(PyExc_SystemError,
747 "globals and locals cannot be NULL");
748 return NULL;
749 }
750 }
751 else if (locals == Py_None)
752 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 if (!PyDict_Check(globals)) {
755 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
756 globals->ob_type->tp_name);
757 return NULL;
758 }
759 if (!PyMapping_Check(locals)) {
760 PyErr_Format(PyExc_TypeError,
761 "arg 3 must be a mapping or None, not %.100s",
762 locals->ob_type->tp_name);
763 return NULL;
764 }
765 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
766 if (PyDict_SetItemString(globals, "__builtins__",
767 PyEval_GetBuiltins()) != 0)
768 return NULL;
769 }
770
771 if (PyCode_Check(prog)) {
772 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
773 PyErr_SetString(PyExc_TypeError,
774 "code object passed to exec() may not "
775 "contain free variables");
776 return NULL;
777 }
778 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
779 }
780 else {
781 char *str;
782 PyCompilerFlags cf;
783 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
784 str = source_as_string(prog, "exec",
785 "string, bytes or code", &cf);
786 if (str == NULL)
787 return NULL;
788 if (PyEval_MergeCompilerFlags(&cf))
789 v = PyRun_StringFlags(str, Py_file_input, globals,
790 locals, &cf);
791 else
792 v = PyRun_String(str, Py_file_input, globals, locals);
793 }
794 if (v == NULL)
795 return NULL;
796 Py_DECREF(v);
797 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000798}
799
800PyDoc_STRVAR(exec_doc,
801"exec(object[, globals[, locals]])\n\
802\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000803Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000804object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000805The globals and locals are dictionaries, defaulting to the current\n\
806globals and locals. If only globals is given, locals defaults to it.");
807
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000808
Guido van Rossum79f25d91997-04-29 20:08:16 +0000809static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000810builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 PyObject *v, *result, *dflt = NULL;
813 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
816 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 if (!PyUnicode_Check(name)) {
819 PyErr_SetString(PyExc_TypeError,
820 "getattr(): attribute name must be string");
821 return NULL;
822 }
823 result = PyObject_GetAttr(v, name);
824 if (result == NULL && dflt != NULL &&
825 PyErr_ExceptionMatches(PyExc_AttributeError))
826 {
827 PyErr_Clear();
828 Py_INCREF(dflt);
829 result = dflt;
830 }
831 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000832}
833
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000834PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000835"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000836\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000837Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
838When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000839exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000840
841
Guido van Rossum79f25d91997-04-29 20:08:16 +0000842static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000843builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 d = PyEval_GetGlobals();
848 Py_XINCREF(d);
849 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000850}
851
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000852PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000853"globals() -> dictionary\n\
854\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000855Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000856
857
Guido van Rossum79f25d91997-04-29 20:08:16 +0000858static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000859builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 PyObject *v;
862 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
865 return NULL;
866 if (!PyUnicode_Check(name)) {
867 PyErr_SetString(PyExc_TypeError,
868 "hasattr(): attribute name must be string");
869 return NULL;
870 }
871 v = PyObject_GetAttr(v, name);
872 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000873 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000875 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000877 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 }
879 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000880 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000881}
882
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000883PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000884"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000885\n\
886Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000887(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000888
889
Guido van Rossum79f25d91997-04-29 20:08:16 +0000890static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000891builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000894}
895
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000896PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000897"id(object) -> integer\n\
898\n\
899Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000900simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000901
902
Raymond Hettingera6c60372008-03-13 01:26:19 +0000903/* map object ************************************************************/
904
905typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 PyObject_HEAD
907 PyObject *iters;
908 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000909} mapobject;
910
Guido van Rossum79f25d91997-04-29 20:08:16 +0000911static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000912map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 PyObject *it, *iters, *func;
915 mapobject *lz;
916 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
919 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 numargs = PyTuple_Size(args);
922 if (numargs < 2) {
923 PyErr_SetString(PyExc_TypeError,
924 "map() must have at least two arguments.");
925 return NULL;
926 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 iters = PyTuple_New(numargs-1);
929 if (iters == NULL)
930 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 for (i=1 ; i<numargs ; i++) {
933 /* Get iterator. */
934 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
935 if (it == NULL) {
936 Py_DECREF(iters);
937 return NULL;
938 }
939 PyTuple_SET_ITEM(iters, i-1, it);
940 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* create mapobject structure */
943 lz = (mapobject *)type->tp_alloc(type, 0);
944 if (lz == NULL) {
945 Py_DECREF(iters);
946 return NULL;
947 }
948 lz->iters = iters;
949 func = PyTuple_GET_ITEM(args, 0);
950 Py_INCREF(func);
951 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000954}
955
956static void
957map_dealloc(mapobject *lz)
958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 PyObject_GC_UnTrack(lz);
960 Py_XDECREF(lz->iters);
961 Py_XDECREF(lz->func);
962 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +0000963}
964
965static int
966map_traverse(mapobject *lz, visitproc visit, void *arg)
967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 Py_VISIT(lz->iters);
969 Py_VISIT(lz->func);
970 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000971}
972
973static PyObject *
974map_next(mapobject *lz)
975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 PyObject *val;
977 PyObject *argtuple;
978 PyObject *result;
979 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 numargs = PyTuple_Size(lz->iters);
982 argtuple = PyTuple_New(numargs);
983 if (argtuple == NULL)
984 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 for (i=0 ; i<numargs ; i++) {
987 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
988 if (val == NULL) {
989 Py_DECREF(argtuple);
990 return NULL;
991 }
992 PyTuple_SET_ITEM(argtuple, i, val);
993 }
994 result = PyObject_Call(lz->func, argtuple, NULL);
995 Py_DECREF(argtuple);
996 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000997}
998
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000999PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001000"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001001\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001002Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001004
Raymond Hettingera6c60372008-03-13 01:26:19 +00001005PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1007 "map", /* tp_name */
1008 sizeof(mapobject), /* tp_basicsize */
1009 0, /* tp_itemsize */
1010 /* methods */
1011 (destructor)map_dealloc, /* tp_dealloc */
1012 0, /* tp_print */
1013 0, /* tp_getattr */
1014 0, /* tp_setattr */
1015 0, /* tp_reserved */
1016 0, /* tp_repr */
1017 0, /* tp_as_number */
1018 0, /* tp_as_sequence */
1019 0, /* tp_as_mapping */
1020 0, /* tp_hash */
1021 0, /* tp_call */
1022 0, /* tp_str */
1023 PyObject_GenericGetAttr, /* tp_getattro */
1024 0, /* tp_setattro */
1025 0, /* tp_as_buffer */
1026 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1027 Py_TPFLAGS_BASETYPE, /* tp_flags */
1028 map_doc, /* tp_doc */
1029 (traverseproc)map_traverse, /* tp_traverse */
1030 0, /* tp_clear */
1031 0, /* tp_richcompare */
1032 0, /* tp_weaklistoffset */
1033 PyObject_SelfIter, /* tp_iter */
1034 (iternextfunc)map_next, /* tp_iternext */
1035 0, /* tp_methods */
1036 0, /* tp_members */
1037 0, /* tp_getset */
1038 0, /* tp_base */
1039 0, /* tp_dict */
1040 0, /* tp_descr_get */
1041 0, /* tp_descr_set */
1042 0, /* tp_dictoffset */
1043 0, /* tp_init */
1044 PyType_GenericAlloc, /* tp_alloc */
1045 map_new, /* tp_new */
1046 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001047};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001048
Guido van Rossum79f25d91997-04-29 20:08:16 +00001049static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001050builtin_next(PyObject *self, PyObject *args)
1051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 PyObject *it, *res;
1053 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1056 return NULL;
1057 if (!PyIter_Check(it)) {
1058 PyErr_Format(PyExc_TypeError,
1059 "%.200s object is not an iterator",
1060 it->ob_type->tp_name);
1061 return NULL;
1062 }
1063
1064 res = (*it->ob_type->tp_iternext)(it);
1065 if (res != NULL) {
1066 return res;
1067 } else if (def != NULL) {
1068 if (PyErr_Occurred()) {
1069 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1070 return NULL;
1071 PyErr_Clear();
1072 }
1073 Py_INCREF(def);
1074 return def;
1075 } else if (PyErr_Occurred()) {
1076 return NULL;
1077 } else {
1078 PyErr_SetNone(PyExc_StopIteration);
1079 return NULL;
1080 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001081}
1082
1083PyDoc_STRVAR(next_doc,
1084"next(iterator[, default])\n\
1085\n\
1086Return the next item from the iterator. If default is given and the iterator\n\
1087is exhausted, it is returned instead of raising StopIteration.");
1088
1089
1090static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001091builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 PyObject *v;
1094 PyObject *name;
1095 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1098 return NULL;
1099 if (PyObject_SetAttr(v, name, value) != 0)
1100 return NULL;
1101 Py_INCREF(Py_None);
1102 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001103}
1104
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001105PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001106"setattr(object, name, value)\n\
1107\n\
1108Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001109``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001110
1111
Guido van Rossum79f25d91997-04-29 20:08:16 +00001112static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001113builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 PyObject *v;
1116 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1119 return NULL;
1120 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1121 return NULL;
1122 Py_INCREF(Py_None);
1123 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001124}
1125
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001126PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001127"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001128\n\
1129Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001130``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001131
1132
Guido van Rossum79f25d91997-04-29 20:08:16 +00001133static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001134builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 x = PyObject_Hash(v);
1139 if (x == -1)
1140 return NULL;
1141 return PyLong_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001142}
1143
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001144PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001145"hash(object) -> integer\n\
1146\n\
1147Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001148the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001149
1150
Guido van Rossum79f25d91997-04-29 20:08:16 +00001151static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001152builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001155}
1156
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001157PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001158"hex(number) -> string\n\
1159\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001160Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001161
1162
Guido van Rossum79f25d91997-04-29 20:08:16 +00001163static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001164builtin_iter(PyObject *self, PyObject *args)
1165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1169 return NULL;
1170 if (w == NULL)
1171 return PyObject_GetIter(v);
1172 if (!PyCallable_Check(v)) {
1173 PyErr_SetString(PyExc_TypeError,
1174 "iter(v, w): v must be callable");
1175 return NULL;
1176 }
1177 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001178}
1179
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001180PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001181"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001182iter(callable, sentinel) -> iterator\n\
1183\n\
1184Get an iterator from an object. In the first form, the argument must\n\
1185supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001186In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001187
1188
1189static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001190builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 res = PyObject_Size(v);
1195 if (res < 0 && PyErr_Occurred())
1196 return NULL;
1197 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001198}
1199
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001200PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001201"len(object) -> integer\n\
1202\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001203Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001204
1205
Guido van Rossum79f25d91997-04-29 20:08:16 +00001206static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001207builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 d = PyEval_GetLocals();
1212 Py_XINCREF(d);
1213 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001214}
1215
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001216PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001217"locals() -> dictionary\n\
1218\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001219Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001220
1221
Guido van Rossum79f25d91997-04-29 20:08:16 +00001222static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001223min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1226 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (PyTuple_Size(args) > 1)
1229 v = args;
1230 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1231 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1234 keyfunc = PyDict_GetItemString(kwds, "key");
1235 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1236 PyErr_Format(PyExc_TypeError,
1237 "%s() got an unexpected keyword argument", name);
1238 return NULL;
1239 }
1240 Py_INCREF(keyfunc);
1241 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 it = PyObject_GetIter(v);
1244 if (it == NULL) {
1245 Py_XDECREF(keyfunc);
1246 return NULL;
1247 }
Tim Petersc3074532001-05-03 07:00:32 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 maxitem = NULL; /* the result */
1250 maxval = NULL; /* the value associated with the result */
1251 while (( item = PyIter_Next(it) )) {
1252 /* get the value from the key function */
1253 if (keyfunc != NULL) {
1254 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1255 if (val == NULL)
1256 goto Fail_it_item;
1257 }
1258 /* no key function; the value is the item */
1259 else {
1260 val = item;
1261 Py_INCREF(val);
1262 }
Tim Petersc3074532001-05-03 07:00:32 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 /* maximum value and item are unset; set them */
1265 if (maxval == NULL) {
1266 maxitem = item;
1267 maxval = val;
1268 }
1269 /* maximum value and item are set; update them as necessary */
1270 else {
1271 int cmp = PyObject_RichCompareBool(val, maxval, op);
1272 if (cmp < 0)
1273 goto Fail_it_item_and_val;
1274 else if (cmp > 0) {
1275 Py_DECREF(maxval);
1276 Py_DECREF(maxitem);
1277 maxval = val;
1278 maxitem = item;
1279 }
1280 else {
1281 Py_DECREF(item);
1282 Py_DECREF(val);
1283 }
1284 }
1285 }
1286 if (PyErr_Occurred())
1287 goto Fail_it;
1288 if (maxval == NULL) {
1289 PyErr_Format(PyExc_ValueError,
1290 "%s() arg is an empty sequence", name);
1291 assert(maxitem == NULL);
1292 }
1293 else
1294 Py_DECREF(maxval);
1295 Py_DECREF(it);
1296 Py_XDECREF(keyfunc);
1297 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001298
1299Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001301Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001303Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 Py_XDECREF(maxval);
1305 Py_XDECREF(maxitem);
1306 Py_DECREF(it);
1307 Py_XDECREF(keyfunc);
1308 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001309}
1310
Guido van Rossum79f25d91997-04-29 20:08:16 +00001311static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001312builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001315}
1316
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001317PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001318"min(iterable[, key=func]) -> value\n\
1319min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001320\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001321With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001322With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001323
1324
Guido van Rossum79f25d91997-04-29 20:08:16 +00001325static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001326builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001329}
1330
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001331PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001332"max(iterable[, key=func]) -> value\n\
1333max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001334\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001335With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001336With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001337
1338
Guido van Rossum79f25d91997-04-29 20:08:16 +00001339static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001340builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001343}
1344
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001345PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001346"oct(number) -> string\n\
1347\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001348Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001349
1350
Guido van Rossum79f25d91997-04-29 20:08:16 +00001351static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001352builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 long ord;
1355 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 if (PyBytes_Check(obj)) {
1358 size = PyBytes_GET_SIZE(obj);
1359 if (size == 1) {
1360 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1361 return PyLong_FromLong(ord);
1362 }
1363 }
1364 else if (PyUnicode_Check(obj)) {
1365 size = PyUnicode_GET_SIZE(obj);
1366 if (size == 1) {
1367 ord = (long)*PyUnicode_AS_UNICODE(obj);
1368 return PyLong_FromLong(ord);
1369 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001370#ifndef Py_UNICODE_WIDE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 if (size == 2) {
1372 /* Decode a valid surrogate pair */
1373 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1374 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1375 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1376 0xDC00 <= c1 && c1 <= 0xDFFF) {
1377 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1378 0x00010000);
1379 return PyLong_FromLong(ord);
1380 }
1381 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001382#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 }
1384 else if (PyByteArray_Check(obj)) {
1385 /* XXX Hopefully this is temporary */
1386 size = PyByteArray_GET_SIZE(obj);
1387 if (size == 1) {
1388 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1389 return PyLong_FromLong(ord);
1390 }
1391 }
1392 else {
1393 PyErr_Format(PyExc_TypeError,
1394 "ord() expected string of length 1, but " \
1395 "%.200s found", obj->ob_type->tp_name);
1396 return NULL;
1397 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 PyErr_Format(PyExc_TypeError,
1400 "ord() expected a character, "
1401 "but string of length %zd found",
1402 size);
1403 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001404}
1405
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001406PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001407"ord(c) -> integer\n\
1408\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001409Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001410)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001411#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001412PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001413"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001414)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001415#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001416;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001417
1418
Guido van Rossum79f25d91997-04-29 20:08:16 +00001419static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001420builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1425 return NULL;
1426 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001427}
1428
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001429PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001430"pow(x, y[, z]) -> number\n\
1431\n\
1432With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001433equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001434
1435
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001436
Guido van Rossum34343512006-11-30 22:13:52 +00001437static PyObject *
1438builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 static char *kwlist[] = {"sep", "end", "file", 0};
1441 static PyObject *dummy_args;
1442 PyObject *sep = NULL, *end = NULL, *file = NULL;
1443 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 if (dummy_args == NULL) {
1446 if (!(dummy_args = PyTuple_New(0)))
1447 return NULL;
1448 }
1449 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1450 kwlist, &sep, &end, &file))
1451 return NULL;
1452 if (file == NULL || file == Py_None) {
1453 file = PySys_GetObject("stdout");
1454 /* sys.stdout may be None when FILE* stdout isn't connected */
1455 if (file == Py_None)
1456 Py_RETURN_NONE;
1457 }
Guido van Rossum34343512006-11-30 22:13:52 +00001458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 if (sep == Py_None) {
1460 sep = NULL;
1461 }
1462 else if (sep && !PyUnicode_Check(sep)) {
1463 PyErr_Format(PyExc_TypeError,
1464 "sep must be None or a string, not %.200s",
1465 sep->ob_type->tp_name);
1466 return NULL;
1467 }
1468 if (end == Py_None) {
1469 end = NULL;
1470 }
1471 else if (end && !PyUnicode_Check(end)) {
1472 PyErr_Format(PyExc_TypeError,
1473 "end must be None or a string, not %.200s",
1474 end->ob_type->tp_name);
1475 return NULL;
1476 }
Guido van Rossum34343512006-11-30 22:13:52 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 for (i = 0; i < PyTuple_Size(args); i++) {
1479 if (i > 0) {
1480 if (sep == NULL)
1481 err = PyFile_WriteString(" ", file);
1482 else
1483 err = PyFile_WriteObject(sep, file,
1484 Py_PRINT_RAW);
1485 if (err)
1486 return NULL;
1487 }
1488 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1489 Py_PRINT_RAW);
1490 if (err)
1491 return NULL;
1492 }
Guido van Rossum34343512006-11-30 22:13:52 +00001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 if (end == NULL)
1495 err = PyFile_WriteString("\n", file);
1496 else
1497 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1498 if (err)
1499 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001502}
1503
1504PyDoc_STRVAR(print_doc,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001505"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001506\n\
1507Prints the values to a stream, or to sys.stdout by default.\n\
1508Optional keyword arguments:\n\
1509file: a file-like object (stream); defaults to the current sys.stdout.\n\
1510sep: string inserted between values, default a space.\n\
1511end: string appended after the last value, default a newline.");
1512
1513
Guido van Rossuma88a0332007-02-26 16:59:55 +00001514static PyObject *
1515builtin_input(PyObject *self, PyObject *args)
1516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 PyObject *promptarg = NULL;
1518 PyObject *fin = PySys_GetObject("stdin");
1519 PyObject *fout = PySys_GetObject("stdout");
1520 PyObject *ferr = PySys_GetObject("stderr");
1521 PyObject *tmp;
1522 long fd;
1523 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 /* Parse arguments */
1526 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1527 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 /* Check that stdin/out/err are intact */
1530 if (fin == NULL || fin == Py_None) {
1531 PyErr_SetString(PyExc_RuntimeError,
1532 "input(): lost sys.stdin");
1533 return NULL;
1534 }
1535 if (fout == NULL || fout == Py_None) {
1536 PyErr_SetString(PyExc_RuntimeError,
1537 "input(): lost sys.stdout");
1538 return NULL;
1539 }
1540 if (ferr == NULL || ferr == Py_None) {
1541 PyErr_SetString(PyExc_RuntimeError,
1542 "input(): lost sys.stderr");
1543 return NULL;
1544 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 /* First of all, flush stderr */
1547 tmp = PyObject_CallMethod(ferr, "flush", "");
1548 if (tmp == NULL)
1549 PyErr_Clear();
1550 else
1551 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 /* We should only use (GNU) readline if Python's sys.stdin and
1554 sys.stdout are the same as C's stdin and stdout, because we
1555 need to pass it those. */
1556 tmp = PyObject_CallMethod(fin, "fileno", "");
1557 if (tmp == NULL) {
1558 PyErr_Clear();
1559 tty = 0;
1560 }
1561 else {
1562 fd = PyLong_AsLong(tmp);
1563 Py_DECREF(tmp);
1564 if (fd < 0 && PyErr_Occurred())
1565 return NULL;
1566 tty = fd == fileno(stdin) && isatty(fd);
1567 }
1568 if (tty) {
1569 tmp = PyObject_CallMethod(fout, "fileno", "");
1570 if (tmp == NULL)
1571 PyErr_Clear();
1572 else {
1573 fd = PyLong_AsLong(tmp);
1574 Py_DECREF(tmp);
1575 if (fd < 0 && PyErr_Occurred())
1576 return NULL;
1577 tty = fd == fileno(stdout) && isatty(fd);
1578 }
1579 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 /* If we're interactive, use (GNU) readline */
1582 if (tty) {
1583 PyObject *po;
1584 char *prompt;
1585 char *s;
1586 PyObject *stdin_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001587 char *stdin_encoding_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 PyObject *result;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1591 if (!stdin_encoding)
1592 /* stdin is a text stream, so it must have an
1593 encoding. */
1594 return NULL;
Victor Stinner306f0102010-05-19 01:06:22 +00001595 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
1596 if (stdin_encoding_str == NULL) {
1597 Py_DECREF(stdin_encoding);
1598 return NULL;
1599 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 tmp = PyObject_CallMethod(fout, "flush", "");
1601 if (tmp == NULL)
1602 PyErr_Clear();
1603 else
1604 Py_DECREF(tmp);
1605 if (promptarg != NULL) {
1606 PyObject *stringpo;
1607 PyObject *stdout_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001608 char *stdout_encoding_str;
1609 stdout_encoding = PyObject_GetAttrString(fout, "encoding");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 if (stdout_encoding == NULL) {
1611 Py_DECREF(stdin_encoding);
1612 return NULL;
1613 }
Victor Stinner306f0102010-05-19 01:06:22 +00001614 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
1615 if (stdout_encoding_str == NULL) {
1616 Py_DECREF(stdin_encoding);
1617 Py_DECREF(stdout_encoding);
1618 return NULL;
1619 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 stringpo = PyObject_Str(promptarg);
1621 if (stringpo == NULL) {
1622 Py_DECREF(stdin_encoding);
1623 Py_DECREF(stdout_encoding);
1624 return NULL;
1625 }
1626 po = PyUnicode_AsEncodedString(stringpo,
Victor Stinner306f0102010-05-19 01:06:22 +00001627 stdout_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 Py_DECREF(stdout_encoding);
1629 Py_DECREF(stringpo);
1630 if (po == NULL) {
1631 Py_DECREF(stdin_encoding);
1632 return NULL;
1633 }
1634 prompt = PyBytes_AsString(po);
1635 if (prompt == NULL) {
1636 Py_DECREF(stdin_encoding);
1637 Py_DECREF(po);
1638 return NULL;
1639 }
1640 }
1641 else {
1642 po = NULL;
1643 prompt = "";
1644 }
1645 s = PyOS_Readline(stdin, stdout, prompt);
1646 Py_XDECREF(po);
1647 if (s == NULL) {
1648 if (!PyErr_Occurred())
1649 PyErr_SetNone(PyExc_KeyboardInterrupt);
1650 Py_DECREF(stdin_encoding);
1651 return NULL;
1652 }
1653 if (*s == '\0') {
1654 PyErr_SetNone(PyExc_EOFError);
1655 result = NULL;
1656 }
1657 else { /* strip trailing '\n' */
1658 size_t len = strlen(s);
1659 if (len > PY_SSIZE_T_MAX) {
1660 PyErr_SetString(PyExc_OverflowError,
1661 "input: input too long");
1662 result = NULL;
1663 }
1664 else {
Victor Stinner306f0102010-05-19 01:06:22 +00001665 result = PyUnicode_Decode(s, len-1, stdin_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 }
1667 }
1668 Py_DECREF(stdin_encoding);
1669 PyMem_FREE(s);
1670 return result;
1671 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 /* Fallback if we're not interactive */
1674 if (promptarg != NULL) {
1675 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1676 return NULL;
1677 }
1678 tmp = PyObject_CallMethod(fout, "flush", "");
1679 if (tmp == NULL)
1680 PyErr_Clear();
1681 else
1682 Py_DECREF(tmp);
1683 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001684}
1685
1686PyDoc_STRVAR(input_doc,
1687"input([prompt]) -> string\n\
1688\n\
1689Read a string from standard input. The trailing newline is stripped.\n\
1690If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1691On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1692is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001693
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001694
Guido van Rossum79f25d91997-04-29 20:08:16 +00001695static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001696builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001699}
1700
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001701PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001702"repr(object) -> string\n\
1703\n\
1704Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001705For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001706
1707
Guido van Rossum79f25d91997-04-29 20:08:16 +00001708static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001709builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 static PyObject *round_str = NULL;
1712 PyObject *ndigits = NULL;
1713 static char *kwlist[] = {"number", "ndigits", 0};
1714 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1717 kwlist, &number, &ndigits))
1718 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 if (Py_TYPE(number)->tp_dict == NULL) {
1721 if (PyType_Ready(Py_TYPE(number)) < 0)
1722 return NULL;
1723 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 if (round_str == NULL) {
1726 round_str = PyUnicode_InternFromString("__round__");
1727 if (round_str == NULL)
1728 return NULL;
1729 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 round = _PyType_Lookup(Py_TYPE(number), round_str);
1732 if (round == NULL) {
1733 PyErr_Format(PyExc_TypeError,
1734 "type %.100s doesn't define __round__ method",
1735 Py_TYPE(number)->tp_name);
1736 return NULL;
1737 }
Alex Martelliae211f92007-08-22 23:21:33 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 if (ndigits == NULL)
1740 return PyObject_CallFunction(round, "O", number);
1741 else
1742 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001743}
1744
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001745PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001746"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001747\n\
1748Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001749This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001750same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001751
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001752
Raymond Hettinger64958a12003-12-17 20:43:33 +00001753static PyObject *
1754builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1757 PyObject *callable;
1758 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1759 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 /* args 1-3 should match listsort in Objects/listobject.c */
1762 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1763 kwlist, &seq, &keyfunc, &reverse))
1764 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 newlist = PySequence_List(seq);
1767 if (newlist == NULL)
1768 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 callable = PyObject_GetAttrString(newlist, "sort");
1771 if (callable == NULL) {
1772 Py_DECREF(newlist);
1773 return NULL;
1774 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 newargs = PyTuple_GetSlice(args, 1, 4);
1777 if (newargs == NULL) {
1778 Py_DECREF(newlist);
1779 Py_DECREF(callable);
1780 return NULL;
1781 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 v = PyObject_Call(callable, newargs, kwds);
1784 Py_DECREF(newargs);
1785 Py_DECREF(callable);
1786 if (v == NULL) {
1787 Py_DECREF(newlist);
1788 return NULL;
1789 }
1790 Py_DECREF(v);
1791 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001792}
1793
1794PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001795"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001796
Guido van Rossum79f25d91997-04-29 20:08:16 +00001797static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001798builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 PyObject *v = NULL;
1801 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1804 return NULL;
1805 if (v == NULL) {
1806 d = PyEval_GetLocals();
1807 if (d == NULL) {
1808 if (!PyErr_Occurred())
1809 PyErr_SetString(PyExc_SystemError,
1810 "vars(): no locals!?");
1811 }
1812 else
1813 Py_INCREF(d);
1814 }
1815 else {
1816 d = PyObject_GetAttrString(v, "__dict__");
1817 if (d == NULL) {
1818 PyErr_SetString(PyExc_TypeError,
1819 "vars() argument must have __dict__ attribute");
1820 return NULL;
1821 }
1822 }
1823 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001824}
1825
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001826PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001827"vars([object]) -> dictionary\n\
1828\n\
1829Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001830With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001831
Alex Martellia70b1912003-04-22 08:12:33 +00001832static PyObject*
1833builtin_sum(PyObject *self, PyObject *args)
1834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 PyObject *seq;
1836 PyObject *result = NULL;
1837 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1840 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 iter = PyObject_GetIter(seq);
1843 if (iter == NULL)
1844 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 if (result == NULL) {
1847 result = PyLong_FromLong(0);
1848 if (result == NULL) {
1849 Py_DECREF(iter);
1850 return NULL;
1851 }
1852 } else {
1853 /* reject string values for 'start' parameter */
1854 if (PyUnicode_Check(result)) {
1855 PyErr_SetString(PyExc_TypeError,
1856 "sum() can't sum strings [use ''.join(seq) instead]");
1857 Py_DECREF(iter);
1858 return NULL;
1859 }
1860 if (PyByteArray_Check(result)) {
1861 PyErr_SetString(PyExc_TypeError,
1862 "sum() can't sum bytes [use b''.join(seq) instead]");
1863 Py_DECREF(iter);
1864 return NULL;
1865 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 Py_INCREF(result);
1868 }
Alex Martellia70b1912003-04-22 08:12:33 +00001869
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001870#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1872 Assumes all inputs are the same type. If the assumption fails, default
1873 to the more general routine.
1874 */
1875 if (PyLong_CheckExact(result)) {
1876 int overflow;
1877 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1878 /* If this already overflowed, don't even enter the loop. */
1879 if (overflow == 0) {
1880 Py_DECREF(result);
1881 result = NULL;
1882 }
1883 while(result == NULL) {
1884 item = PyIter_Next(iter);
1885 if (item == NULL) {
1886 Py_DECREF(iter);
1887 if (PyErr_Occurred())
1888 return NULL;
1889 return PyLong_FromLong(i_result);
1890 }
1891 if (PyLong_CheckExact(item)) {
1892 long b = PyLong_AsLongAndOverflow(item, &overflow);
1893 long x = i_result + b;
1894 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1895 i_result = x;
1896 Py_DECREF(item);
1897 continue;
1898 }
1899 }
1900 /* Either overflowed or is not an int. Restore real objects and process normally */
1901 result = PyLong_FromLong(i_result);
1902 temp = PyNumber_Add(result, item);
1903 Py_DECREF(result);
1904 Py_DECREF(item);
1905 result = temp;
1906 if (result == NULL) {
1907 Py_DECREF(iter);
1908 return NULL;
1909 }
1910 }
1911 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 if (PyFloat_CheckExact(result)) {
1914 double f_result = PyFloat_AS_DOUBLE(result);
1915 Py_DECREF(result);
1916 result = NULL;
1917 while(result == NULL) {
1918 item = PyIter_Next(iter);
1919 if (item == NULL) {
1920 Py_DECREF(iter);
1921 if (PyErr_Occurred())
1922 return NULL;
1923 return PyFloat_FromDouble(f_result);
1924 }
1925 if (PyFloat_CheckExact(item)) {
1926 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1927 f_result += PyFloat_AS_DOUBLE(item);
1928 PyFPE_END_PROTECT(f_result)
1929 Py_DECREF(item);
1930 continue;
1931 }
1932 if (PyLong_CheckExact(item)) {
1933 long value;
1934 int overflow;
1935 value = PyLong_AsLongAndOverflow(item, &overflow);
1936 if (!overflow) {
1937 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1938 f_result += (double)value;
1939 PyFPE_END_PROTECT(f_result)
1940 Py_DECREF(item);
1941 continue;
1942 }
1943 }
1944 result = PyFloat_FromDouble(f_result);
1945 temp = PyNumber_Add(result, item);
1946 Py_DECREF(result);
1947 Py_DECREF(item);
1948 result = temp;
1949 if (result == NULL) {
1950 Py_DECREF(iter);
1951 return NULL;
1952 }
1953 }
1954 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001955#endif
1956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 for(;;) {
1958 item = PyIter_Next(iter);
1959 if (item == NULL) {
1960 /* error, or end-of-sequence */
1961 if (PyErr_Occurred()) {
1962 Py_DECREF(result);
1963 result = NULL;
1964 }
1965 break;
1966 }
1967 /* It's tempting to use PyNumber_InPlaceAdd instead of
1968 PyNumber_Add here, to avoid quadratic running time
1969 when doing 'sum(list_of_lists, [])'. However, this
1970 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00001971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 empty = []
1973 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00001974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 would change the value of empty. */
1976 temp = PyNumber_Add(result, item);
1977 Py_DECREF(result);
1978 Py_DECREF(item);
1979 result = temp;
1980 if (result == NULL)
1981 break;
1982 }
1983 Py_DECREF(iter);
1984 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00001985}
1986
1987PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001988"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00001989\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00001990Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
1991of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00001992empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00001993
1994
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001995static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001996builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 PyObject *inst;
1999 PyObject *cls;
2000 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2003 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 retval = PyObject_IsInstance(inst, cls);
2006 if (retval < 0)
2007 return NULL;
2008 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002009}
2010
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002011PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002012"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002013\n\
2014Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002015With a type as second argument, return whether that is the object's type.\n\
2016The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002017isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002018
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002019
2020static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002021builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 PyObject *derived;
2024 PyObject *cls;
2025 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2028 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 retval = PyObject_IsSubclass(derived, cls);
2031 if (retval < 0)
2032 return NULL;
2033 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002034}
2035
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002036PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002037"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002038\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002039Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2040When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2041is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002042
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002043
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002044typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 PyObject_HEAD
2046 Py_ssize_t tuplesize;
2047 PyObject *ittuple; /* tuple of iterators */
2048 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002049} zipobject;
2050
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002051static PyObject *
2052zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 zipobject *lz;
2055 Py_ssize_t i;
2056 PyObject *ittuple; /* tuple of iterators */
2057 PyObject *result;
2058 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2061 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 /* args must be a tuple */
2064 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 /* obtain iterators */
2067 ittuple = PyTuple_New(tuplesize);
2068 if (ittuple == NULL)
2069 return NULL;
2070 for (i=0; i < tuplesize; ++i) {
2071 PyObject *item = PyTuple_GET_ITEM(args, i);
2072 PyObject *it = PyObject_GetIter(item);
2073 if (it == NULL) {
2074 if (PyErr_ExceptionMatches(PyExc_TypeError))
2075 PyErr_Format(PyExc_TypeError,
2076 "zip argument #%zd must support iteration",
2077 i+1);
2078 Py_DECREF(ittuple);
2079 return NULL;
2080 }
2081 PyTuple_SET_ITEM(ittuple, i, it);
2082 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 /* create a result holder */
2085 result = PyTuple_New(tuplesize);
2086 if (result == NULL) {
2087 Py_DECREF(ittuple);
2088 return NULL;
2089 }
2090 for (i=0 ; i < tuplesize ; i++) {
2091 Py_INCREF(Py_None);
2092 PyTuple_SET_ITEM(result, i, Py_None);
2093 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 /* create zipobject structure */
2096 lz = (zipobject *)type->tp_alloc(type, 0);
2097 if (lz == NULL) {
2098 Py_DECREF(ittuple);
2099 Py_DECREF(result);
2100 return NULL;
2101 }
2102 lz->ittuple = ittuple;
2103 lz->tuplesize = tuplesize;
2104 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002107}
2108
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002109static void
2110zip_dealloc(zipobject *lz)
2111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 PyObject_GC_UnTrack(lz);
2113 Py_XDECREF(lz->ittuple);
2114 Py_XDECREF(lz->result);
2115 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002116}
2117
2118static int
2119zip_traverse(zipobject *lz, visitproc visit, void *arg)
2120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 Py_VISIT(lz->ittuple);
2122 Py_VISIT(lz->result);
2123 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002124}
2125
2126static PyObject *
2127zip_next(zipobject *lz)
2128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 Py_ssize_t i;
2130 Py_ssize_t tuplesize = lz->tuplesize;
2131 PyObject *result = lz->result;
2132 PyObject *it;
2133 PyObject *item;
2134 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 if (tuplesize == 0)
2137 return NULL;
2138 if (Py_REFCNT(result) == 1) {
2139 Py_INCREF(result);
2140 for (i=0 ; i < tuplesize ; i++) {
2141 it = PyTuple_GET_ITEM(lz->ittuple, i);
2142 item = (*Py_TYPE(it)->tp_iternext)(it);
2143 if (item == NULL) {
2144 Py_DECREF(result);
2145 return NULL;
2146 }
2147 olditem = PyTuple_GET_ITEM(result, i);
2148 PyTuple_SET_ITEM(result, i, item);
2149 Py_DECREF(olditem);
2150 }
2151 } else {
2152 result = PyTuple_New(tuplesize);
2153 if (result == NULL)
2154 return NULL;
2155 for (i=0 ; i < tuplesize ; i++) {
2156 it = PyTuple_GET_ITEM(lz->ittuple, i);
2157 item = (*Py_TYPE(it)->tp_iternext)(it);
2158 if (item == NULL) {
2159 Py_DECREF(result);
2160 return NULL;
2161 }
2162 PyTuple_SET_ITEM(result, i, item);
2163 }
2164 }
2165 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002166}
Barry Warsawbd599b52000-08-03 15:45:29 +00002167
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002168PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002169"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002170\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002171Return a zip object whose .__next__() method returns a tuple where\n\
2172the i-th element comes from the i-th iterable argument. The .__next__()\n\
2173method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002174is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002175
2176PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2178 "zip", /* tp_name */
2179 sizeof(zipobject), /* tp_basicsize */
2180 0, /* tp_itemsize */
2181 /* methods */
2182 (destructor)zip_dealloc, /* tp_dealloc */
2183 0, /* tp_print */
2184 0, /* tp_getattr */
2185 0, /* tp_setattr */
2186 0, /* tp_reserved */
2187 0, /* tp_repr */
2188 0, /* tp_as_number */
2189 0, /* tp_as_sequence */
2190 0, /* tp_as_mapping */
2191 0, /* tp_hash */
2192 0, /* tp_call */
2193 0, /* tp_str */
2194 PyObject_GenericGetAttr, /* tp_getattro */
2195 0, /* tp_setattro */
2196 0, /* tp_as_buffer */
2197 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2198 Py_TPFLAGS_BASETYPE, /* tp_flags */
2199 zip_doc, /* tp_doc */
2200 (traverseproc)zip_traverse, /* tp_traverse */
2201 0, /* tp_clear */
2202 0, /* tp_richcompare */
2203 0, /* tp_weaklistoffset */
2204 PyObject_SelfIter, /* tp_iter */
2205 (iternextfunc)zip_next, /* tp_iternext */
2206 0, /* tp_methods */
2207 0, /* tp_members */
2208 0, /* tp_getset */
2209 0, /* tp_base */
2210 0, /* tp_dict */
2211 0, /* tp_descr_get */
2212 0, /* tp_descr_set */
2213 0, /* tp_dictoffset */
2214 0, /* tp_init */
2215 PyType_GenericAlloc, /* tp_alloc */
2216 zip_new, /* tp_new */
2217 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002218};
Barry Warsawbd599b52000-08-03 15:45:29 +00002219
2220
Guido van Rossum79f25d91997-04-29 20:08:16 +00002221static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 {"__build_class__", (PyCFunction)builtin___build_class__,
2223 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2224 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2225 {"abs", builtin_abs, METH_O, abs_doc},
2226 {"all", builtin_all, METH_O, all_doc},
2227 {"any", builtin_any, METH_O, any_doc},
2228 {"ascii", builtin_ascii, METH_O, ascii_doc},
2229 {"bin", builtin_bin, METH_O, bin_doc},
2230 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2231 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2232 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2233 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2234 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2235 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2236 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2237 {"format", builtin_format, METH_VARARGS, format_doc},
2238 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2239 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2240 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2241 {"hash", builtin_hash, METH_O, hash_doc},
2242 {"hex", builtin_hex, METH_O, hex_doc},
2243 {"id", builtin_id, METH_O, id_doc},
2244 {"input", builtin_input, METH_VARARGS, input_doc},
2245 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2246 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2247 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2248 {"len", builtin_len, METH_O, len_doc},
2249 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2250 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2251 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2252 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2253 {"oct", builtin_oct, METH_O, oct_doc},
2254 {"ord", builtin_ord, METH_O, ord_doc},
2255 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2256 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2257 {"repr", builtin_repr, METH_O, repr_doc},
2258 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2259 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2260 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2261 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2262 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2263 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002264};
2265
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002266PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002267"Built-in functions, exceptions, and other objects.\n\
2268\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002269Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002270
Martin v. Löwis1a214512008-06-11 05:26:20 +00002271static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 PyModuleDef_HEAD_INIT,
2273 "builtins",
2274 builtin_doc,
2275 -1, /* multiple "initialization" just copies the module dict. */
2276 builtin_methods,
2277 NULL,
2278 NULL,
2279 NULL,
2280 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002281};
2282
2283
Guido van Rossum25ce5661997-08-02 03:10:38 +00002284PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002285_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 PyObject *mod, *dict, *debug;
2288 mod = PyModule_Create(&builtinsmodule);
2289 if (mod == NULL)
2290 return NULL;
2291 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002292
Tim Peters7571a0f2003-03-23 17:52:28 +00002293#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 /* "builtins" exposes a number of statically allocated objects
2295 * that, before this code was added in 2.3, never showed up in
2296 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2297 * result, programs leaking references to None and False (etc)
2298 * couldn't be diagnosed by examining sys.getobjects(0).
2299 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002300#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2301#else
2302#define ADD_TO_ALL(OBJECT) (void)0
2303#endif
2304
Tim Peters4b7625e2001-09-13 21:37:17 +00002305#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2307 return NULL; \
2308 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 SETBUILTIN("None", Py_None);
2311 SETBUILTIN("Ellipsis", Py_Ellipsis);
2312 SETBUILTIN("NotImplemented", Py_NotImplemented);
2313 SETBUILTIN("False", Py_False);
2314 SETBUILTIN("True", Py_True);
2315 SETBUILTIN("bool", &PyBool_Type);
2316 SETBUILTIN("memoryview", &PyMemoryView_Type);
2317 SETBUILTIN("bytearray", &PyByteArray_Type);
2318 SETBUILTIN("bytes", &PyBytes_Type);
2319 SETBUILTIN("classmethod", &PyClassMethod_Type);
2320 SETBUILTIN("complex", &PyComplex_Type);
2321 SETBUILTIN("dict", &PyDict_Type);
2322 SETBUILTIN("enumerate", &PyEnum_Type);
2323 SETBUILTIN("filter", &PyFilter_Type);
2324 SETBUILTIN("float", &PyFloat_Type);
2325 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2326 SETBUILTIN("property", &PyProperty_Type);
2327 SETBUILTIN("int", &PyLong_Type);
2328 SETBUILTIN("list", &PyList_Type);
2329 SETBUILTIN("map", &PyMap_Type);
2330 SETBUILTIN("object", &PyBaseObject_Type);
2331 SETBUILTIN("range", &PyRange_Type);
2332 SETBUILTIN("reversed", &PyReversed_Type);
2333 SETBUILTIN("set", &PySet_Type);
2334 SETBUILTIN("slice", &PySlice_Type);
2335 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2336 SETBUILTIN("str", &PyUnicode_Type);
2337 SETBUILTIN("super", &PySuper_Type);
2338 SETBUILTIN("tuple", &PyTuple_Type);
2339 SETBUILTIN("type", &PyType_Type);
2340 SETBUILTIN("zip", &PyZip_Type);
2341 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2342 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2343 Py_XDECREF(debug);
2344 return NULL;
2345 }
2346 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002349#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002350#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002351}