blob: e1f2931dbc2952f82676f2fb3c07d061ab752738 [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
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000036int
37_Py_SetFileSystemEncoding(PyObject *s)
38{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 PyObject *defenc, *codec;
40 if (!PyUnicode_Check(s)) {
41 PyErr_BadInternalCall();
42 return -1;
43 }
44 defenc = _PyUnicode_AsDefaultEncodedString(s, NULL);
45 if (!defenc)
46 return -1;
47 codec = _PyCodec_Lookup(PyBytes_AsString(defenc));
48 if (codec == NULL)
49 return -1;
50 Py_DECREF(codec);
51 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding)
52 /* A file system encoding was set at run-time */
53 free((char*)Py_FileSystemDefaultEncoding);
54 Py_FileSystemDefaultEncoding = strdup(PyBytes_AsString(defenc));
55 Py_HasFileSystemDefaultEncoding = 0;
56 return 0;
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000057}
58
Guido van Rossum79f25d91997-04-29 20:08:16 +000059static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000060builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
61{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell;
63 PyObject *cls = NULL;
64 Py_ssize_t nargs, nbases;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000066 assert(args != NULL);
67 if (!PyTuple_Check(args)) {
68 PyErr_SetString(PyExc_TypeError,
69 "__build_class__: args is not a tuple");
70 return NULL;
71 }
72 nargs = PyTuple_GET_SIZE(args);
73 if (nargs < 2) {
74 PyErr_SetString(PyExc_TypeError,
75 "__build_class__: not enough arguments");
76 return NULL;
77 }
78 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
79 name = PyTuple_GET_ITEM(args, 1);
80 if (!PyUnicode_Check(name)) {
81 PyErr_SetString(PyExc_TypeError,
82 "__build_class__: name is not a string");
83 return NULL;
84 }
85 bases = PyTuple_GetSlice(args, 2, nargs);
86 if (bases == NULL)
87 return NULL;
88 nbases = nargs - 2;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090 if (kwds == NULL) {
91 meta = NULL;
92 mkw = NULL;
93 }
94 else {
95 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
96 if (mkw == NULL) {
97 Py_DECREF(bases);
98 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000099 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 meta = PyDict_GetItemString(mkw, "metaclass");
101 if (meta != NULL) {
102 Py_INCREF(meta);
103 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
104 Py_DECREF(meta);
105 Py_DECREF(mkw);
106 Py_DECREF(bases);
107 return NULL;
108 }
109 }
110 }
111 if (meta == NULL) {
112 if (PyTuple_GET_SIZE(bases) == 0)
113 meta = (PyObject *) (&PyType_Type);
114 else {
115 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
116 meta = (PyObject *) (base0->ob_type);
117 }
118 Py_INCREF(meta);
119 }
120 prep = PyObject_GetAttrString(meta, "__prepare__");
121 if (prep == NULL) {
122 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
123 PyErr_Clear();
124 ns = PyDict_New();
125 }
126 else {
127 Py_DECREF(meta);
128 Py_XDECREF(mkw);
129 Py_DECREF(bases);
130 return NULL;
131 }
132 }
133 else {
134 PyObject *pargs = PyTuple_Pack(2, name, bases);
135 if (pargs == NULL) {
136 Py_DECREF(prep);
137 Py_DECREF(meta);
138 Py_XDECREF(mkw);
139 Py_DECREF(bases);
140 return NULL;
141 }
142 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
143 Py_DECREF(pargs);
144 Py_DECREF(prep);
145 }
146 if (ns == NULL) {
147 Py_DECREF(meta);
148 Py_XDECREF(mkw);
149 Py_DECREF(bases);
150 return NULL;
151 }
152 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
153 if (cell != NULL) {
154 PyObject *margs;
155 margs = PyTuple_Pack(3, name, bases, ns);
156 if (margs != NULL) {
157 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
158 Py_DECREF(margs);
159 }
160 if (cls != NULL && PyCell_Check(cell)) {
161 Py_INCREF(cls);
162 PyCell_SET(cell, cls);
163 }
164 Py_DECREF(cell);
165 }
166 Py_DECREF(ns);
167 Py_DECREF(meta);
168 Py_XDECREF(mkw);
169 Py_DECREF(bases);
170 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000171}
172
173PyDoc_STRVAR(build_class_doc,
174"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
175\n\
176Internal helper function used by the class statement.");
177
178static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000179builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
182 "level", 0};
183 char *name;
184 PyObject *globals = NULL;
185 PyObject *locals = NULL;
186 PyObject *fromlist = NULL;
187 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
190 kwlist, &name, &globals, &locals, &fromlist, &level))
191 return NULL;
192 return PyImport_ImportModuleLevel(name, globals, locals,
193 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000194}
195
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000196PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000197"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000198\n\
199Import a module. The globals are only used to determine the context;\n\
200they are not modified. The locals are currently unused. The fromlist\n\
201should be a list of names to emulate ``from name import ...'', or an\n\
202empty list to emulate ``import name''.\n\
203When importing a module from a package, note that __import__('A.B', ...)\n\
204returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000205fromlist is not empty. Level is used to determine whether to perform \n\
206absolute or relative imports. -1 is the original strategy of attempting\n\
207both absolute and relative imports, 0 is absolute, a positive number\n\
208is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000209
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000210
Guido van Rossum79f25d91997-04-29 20:08:16 +0000211static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000212builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000215}
216
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000217PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000218"abs(number) -> number\n\
219\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000220Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000221
Raymond Hettinger96229b12005-03-11 06:49:40 +0000222static PyObject *
223builtin_all(PyObject *self, PyObject *v)
224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 PyObject *it, *item;
226 PyObject *(*iternext)(PyObject *);
227 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 it = PyObject_GetIter(v);
230 if (it == NULL)
231 return NULL;
232 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 for (;;) {
235 item = iternext(it);
236 if (item == NULL)
237 break;
238 cmp = PyObject_IsTrue(item);
239 Py_DECREF(item);
240 if (cmp < 0) {
241 Py_DECREF(it);
242 return NULL;
243 }
244 if (cmp == 0) {
245 Py_DECREF(it);
246 Py_RETURN_FALSE;
247 }
248 }
249 Py_DECREF(it);
250 if (PyErr_Occurred()) {
251 if (PyErr_ExceptionMatches(PyExc_StopIteration))
252 PyErr_Clear();
253 else
254 return NULL;
255 }
256 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000257}
258
259PyDoc_STRVAR(all_doc,
260"all(iterable) -> bool\n\
261\n\
262Return True if bool(x) is True for all values x in the iterable.");
263
264static PyObject *
265builtin_any(PyObject *self, PyObject *v)
266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 PyObject *it, *item;
268 PyObject *(*iternext)(PyObject *);
269 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 it = PyObject_GetIter(v);
272 if (it == NULL)
273 return NULL;
274 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 for (;;) {
277 item = iternext(it);
278 if (item == NULL)
279 break;
280 cmp = PyObject_IsTrue(item);
281 Py_DECREF(item);
282 if (cmp < 0) {
283 Py_DECREF(it);
284 return NULL;
285 }
286 if (cmp == 1) {
287 Py_DECREF(it);
288 Py_RETURN_TRUE;
289 }
290 }
291 Py_DECREF(it);
292 if (PyErr_Occurred()) {
293 if (PyErr_ExceptionMatches(PyExc_StopIteration))
294 PyErr_Clear();
295 else
296 return NULL;
297 }
298 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000299}
300
301PyDoc_STRVAR(any_doc,
302"any(iterable) -> bool\n\
303\n\
304Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000305
Georg Brandl559e5d72008-06-11 18:37:52 +0000306static PyObject *
307builtin_ascii(PyObject *self, PyObject *v)
308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000310}
311
312PyDoc_STRVAR(ascii_doc,
313"ascii(object) -> string\n\
314\n\
315As repr(), return a string containing a printable representation of an\n\
316object, but escape the non-ASCII characters in the string returned by\n\
317repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
318to that returned by repr() in Python 2.");
319
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000320
Guido van Rossum79f25d91997-04-29 20:08:16 +0000321static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000322builtin_bin(PyObject *self, PyObject *v)
323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000325}
326
327PyDoc_STRVAR(bin_doc,
328"bin(number) -> string\n\
329\n\
330Return the binary representation of an integer or long integer.");
331
332
Raymond Hettinger17301e92008-03-13 00:19:26 +0000333typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 PyObject_HEAD
335 PyObject *func;
336 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000337} filterobject;
338
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000339static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000340filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 PyObject *func, *seq;
343 PyObject *it;
344 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
347 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
350 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 /* Get iterator. */
353 it = PyObject_GetIter(seq);
354 if (it == NULL)
355 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 /* create filterobject structure */
358 lz = (filterobject *)type->tp_alloc(type, 0);
359 if (lz == NULL) {
360 Py_DECREF(it);
361 return NULL;
362 }
363 Py_INCREF(func);
364 lz->func = func;
365 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000368}
369
370static void
371filter_dealloc(filterobject *lz)
372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 PyObject_GC_UnTrack(lz);
374 Py_XDECREF(lz->func);
375 Py_XDECREF(lz->it);
376 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000377}
378
379static int
380filter_traverse(filterobject *lz, visitproc visit, void *arg)
381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 Py_VISIT(lz->it);
383 Py_VISIT(lz->func);
384 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000385}
386
387static PyObject *
388filter_next(filterobject *lz)
389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 PyObject *item;
391 PyObject *it = lz->it;
392 long ok;
393 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 iternext = *Py_TYPE(it)->tp_iternext;
396 for (;;) {
397 item = iternext(it);
398 if (item == NULL)
399 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
402 ok = PyObject_IsTrue(item);
403 } else {
404 PyObject *good;
405 good = PyObject_CallFunctionObjArgs(lz->func,
406 item, NULL);
407 if (good == NULL) {
408 Py_DECREF(item);
409 return NULL;
410 }
411 ok = PyObject_IsTrue(good);
412 Py_DECREF(good);
413 }
414 if (ok)
415 return item;
416 Py_DECREF(item);
417 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000418}
419
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000420PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000421"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000422\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000423Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000424is true. If function is None, return the items that are true.");
425
426PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 PyVarObject_HEAD_INIT(&PyType_Type, 0)
428 "filter", /* tp_name */
429 sizeof(filterobject), /* tp_basicsize */
430 0, /* tp_itemsize */
431 /* methods */
432 (destructor)filter_dealloc, /* tp_dealloc */
433 0, /* tp_print */
434 0, /* tp_getattr */
435 0, /* tp_setattr */
436 0, /* tp_reserved */
437 0, /* tp_repr */
438 0, /* tp_as_number */
439 0, /* tp_as_sequence */
440 0, /* tp_as_mapping */
441 0, /* tp_hash */
442 0, /* tp_call */
443 0, /* tp_str */
444 PyObject_GenericGetAttr, /* tp_getattro */
445 0, /* tp_setattro */
446 0, /* tp_as_buffer */
447 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
448 Py_TPFLAGS_BASETYPE, /* tp_flags */
449 filter_doc, /* tp_doc */
450 (traverseproc)filter_traverse, /* tp_traverse */
451 0, /* tp_clear */
452 0, /* tp_richcompare */
453 0, /* tp_weaklistoffset */
454 PyObject_SelfIter, /* tp_iter */
455 (iternextfunc)filter_next, /* tp_iternext */
456 0, /* tp_methods */
457 0, /* tp_members */
458 0, /* tp_getset */
459 0, /* tp_base */
460 0, /* tp_dict */
461 0, /* tp_descr_get */
462 0, /* tp_descr_set */
463 0, /* tp_dictoffset */
464 0, /* tp_init */
465 PyType_GenericAlloc, /* tp_alloc */
466 filter_new, /* tp_new */
467 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000468};
469
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000470
Eric Smith8c663262007-08-25 02:26:07 +0000471static PyObject *
472builtin_format(PyObject *self, PyObject *args)
473{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000474 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000475 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000476
Eric Smith8fd3eba2008-02-17 19:48:00 +0000477 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000479
Eric Smith8fd3eba2008-02-17 19:48:00 +0000480 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000481}
482
Eric Smith8c663262007-08-25 02:26:07 +0000483PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000484"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000485\n\
Eric Smith81936692007-08-31 01:14:01 +0000486Returns value.__format__(format_spec)\n\
487format_spec defaults to \"\"");
488
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000489static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000490builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 if (!PyArg_ParseTuple(args, "i:chr", &x))
495 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000498}
499
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000500PyDoc_VAR(chr_doc) = PyDoc_STR(
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000501"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000502\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000503Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000504)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000505#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000506PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000507"\nIf 0x10000 <= i, a surrogate pair is returned."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000508)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000509#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000510;
Guido van Rossum09095f32000-03-10 23:00:52 +0000511
512
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000513static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000514source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 char *str;
517 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 if (PyUnicode_Check(cmd)) {
520 cf->cf_flags |= PyCF_IGNORE_COOKIE;
521 cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL);
522 if (cmd == NULL)
523 return NULL;
524 }
525 else if (!PyObject_CheckReadBuffer(cmd)) {
526 PyErr_Format(PyExc_TypeError,
527 "%s() arg 1 must be a %s object",
528 funcname, what);
529 return NULL;
530 }
531 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
532 return NULL;
533 }
534 if (strlen(str) != size) {
535 PyErr_SetString(PyExc_TypeError,
536 "source code string cannot contain null bytes");
537 return NULL;
538 }
539 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000540}
541
Guido van Rossum79f25d91997-04-29 20:08:16 +0000542static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000543builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 char *str;
546 char *filename;
547 char *startstr;
548 int mode = -1;
549 int dont_inherit = 0;
550 int supplied_flags = 0;
551 int is_ast;
552 PyCompilerFlags cf;
553 PyObject *cmd;
554 static char *kwlist[] = {"source", "filename", "mode", "flags",
555 "dont_inherit", NULL};
556 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
559 kwlist, &cmd, &filename, &startstr,
560 &supplied_flags, &dont_inherit))
561 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 if (supplied_flags &
566 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
567 {
568 PyErr_SetString(PyExc_ValueError,
569 "compile(): unrecognised flags");
570 return NULL;
571 }
572 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 if (!dont_inherit) {
575 PyEval_MergeCompilerFlags(&cf);
576 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 if (strcmp(startstr, "exec") == 0)
579 mode = 0;
580 else if (strcmp(startstr, "eval") == 0)
581 mode = 1;
582 else if (strcmp(startstr, "single") == 0)
583 mode = 2;
584 else {
585 PyErr_SetString(PyExc_ValueError,
586 "compile() arg 3 must be 'exec', 'eval' or 'single'");
587 return NULL;
588 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 is_ast = PyAST_Check(cmd);
591 if (is_ast == -1)
592 return NULL;
593 if (is_ast) {
594 PyObject *result;
595 if (supplied_flags & PyCF_ONLY_AST) {
596 Py_INCREF(cmd);
597 result = cmd;
598 }
599 else {
600 PyArena *arena;
601 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 arena = PyArena_New();
604 mod = PyAST_obj2mod(cmd, arena, mode);
605 if (mod == NULL) {
606 PyArena_Free(arena);
607 return NULL;
608 }
609 result = (PyObject*)PyAST_Compile(mod, filename,
610 &cf, arena);
611 PyArena_Free(arena);
612 }
613 return result;
614 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
617 if (str == NULL)
618 return NULL;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 return Py_CompileStringFlags(str, filename, start[mode], &cf);
Guido van Rossum5b722181993-03-30 17:46:03 +0000621}
622
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000623PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000624"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000625\n\
626Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000627into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000628The filename will be used for run-time error messages.\n\
629The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000630single (interactive) statement, or 'eval' to compile an expression.\n\
631The flags argument, if present, controls which future statements influence\n\
632the compilation of the code.\n\
633The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
634the effects of any future statements in effect in the code calling\n\
635compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000636in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000637
Guido van Rossum79f25d91997-04-29 20:08:16 +0000638static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000639builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
644 return NULL;
645 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000646}
647
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000648PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000649"dir([object]) -> list of strings\n"
650"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000651"If called without an argument, return the names in the current scope.\n"
652"Else, return an alphabetized list of names comprising (some of) the attributes\n"
653"of the given object, and of attributes reachable from it.\n"
654"If the object supplies a method named __dir__, it will be used; otherwise\n"
655"the default dir() logic is used and returns:\n"
656" for a module object: the module's attributes.\n"
657" for a class object: its attributes, and recursively the attributes\n"
658" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000659" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000660" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000661
Guido van Rossum79f25d91997-04-29 20:08:16 +0000662static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000663builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
668 return NULL;
669 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000670}
671
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000672PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000673"divmod(x, y) -> (div, mod)\n\
674\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000675Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000676
677
Guido van Rossum79f25d91997-04-29 20:08:16 +0000678static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000679builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 PyObject *cmd, *result, *tmp = NULL;
682 PyObject *globals = Py_None, *locals = Py_None;
683 char *str;
684 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
687 return NULL;
688 if (locals != Py_None && !PyMapping_Check(locals)) {
689 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
690 return NULL;
691 }
692 if (globals != Py_None && !PyDict_Check(globals)) {
693 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
694 "globals must be a real dict; try eval(expr, {}, mapping)"
695 : "globals must be a dict");
696 return NULL;
697 }
698 if (globals == Py_None) {
699 globals = PyEval_GetGlobals();
700 if (locals == Py_None)
701 locals = PyEval_GetLocals();
702 }
703 else if (locals == Py_None)
704 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 if (globals == NULL || locals == NULL) {
707 PyErr_SetString(PyExc_TypeError,
708 "eval must be given globals and locals "
709 "when called without a frame");
710 return NULL;
711 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
714 if (PyDict_SetItemString(globals, "__builtins__",
715 PyEval_GetBuiltins()) != 0)
716 return NULL;
717 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 if (PyCode_Check(cmd)) {
720 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
721 PyErr_SetString(PyExc_TypeError,
722 "code object passed to eval() may not contain free variables");
723 return NULL;
724 }
725 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
726 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
729 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
730 if (str == NULL)
731 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 while (*str == ' ' || *str == '\t')
734 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 (void)PyEval_MergeCompilerFlags(&cf);
737 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
738 Py_XDECREF(tmp);
739 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000740}
741
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000742PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000743"eval(source[, globals[, locals]]) -> value\n\
744\n\
745Evaluate the source in the context of globals and locals.\n\
746The source may be a string representing a Python expression\n\
747or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000748The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000749defaulting to the current globals and locals.\n\
750If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000751
Georg Brandl7cae87c2006-09-06 06:51:57 +0000752static PyObject *
753builtin_exec(PyObject *self, PyObject *args)
754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 PyObject *v;
756 PyObject *prog, *globals = Py_None, *locals = Py_None;
757 int plain = 0;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
760 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 if (globals == Py_None) {
763 globals = PyEval_GetGlobals();
764 if (locals == Py_None) {
765 locals = PyEval_GetLocals();
766 plain = 1;
767 }
768 if (!globals || !locals) {
769 PyErr_SetString(PyExc_SystemError,
770 "globals and locals cannot be NULL");
771 return NULL;
772 }
773 }
774 else if (locals == Py_None)
775 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 if (!PyDict_Check(globals)) {
778 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
779 globals->ob_type->tp_name);
780 return NULL;
781 }
782 if (!PyMapping_Check(locals)) {
783 PyErr_Format(PyExc_TypeError,
784 "arg 3 must be a mapping or None, not %.100s",
785 locals->ob_type->tp_name);
786 return NULL;
787 }
788 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
789 if (PyDict_SetItemString(globals, "__builtins__",
790 PyEval_GetBuiltins()) != 0)
791 return NULL;
792 }
793
794 if (PyCode_Check(prog)) {
795 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
796 PyErr_SetString(PyExc_TypeError,
797 "code object passed to exec() may not "
798 "contain free variables");
799 return NULL;
800 }
801 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
802 }
803 else {
804 char *str;
805 PyCompilerFlags cf;
806 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
807 str = source_as_string(prog, "exec",
808 "string, bytes or code", &cf);
809 if (str == NULL)
810 return NULL;
811 if (PyEval_MergeCompilerFlags(&cf))
812 v = PyRun_StringFlags(str, Py_file_input, globals,
813 locals, &cf);
814 else
815 v = PyRun_String(str, Py_file_input, globals, locals);
816 }
817 if (v == NULL)
818 return NULL;
819 Py_DECREF(v);
820 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000821}
822
823PyDoc_STRVAR(exec_doc,
824"exec(object[, globals[, locals]])\n\
825\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000826Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000827object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000828The globals and locals are dictionaries, defaulting to the current\n\
829globals and locals. If only globals is given, locals defaults to it.");
830
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000831
Guido van Rossum79f25d91997-04-29 20:08:16 +0000832static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000833builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 PyObject *v, *result, *dflt = NULL;
836 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
839 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 if (!PyUnicode_Check(name)) {
842 PyErr_SetString(PyExc_TypeError,
843 "getattr(): attribute name must be string");
844 return NULL;
845 }
846 result = PyObject_GetAttr(v, name);
847 if (result == NULL && dflt != NULL &&
848 PyErr_ExceptionMatches(PyExc_AttributeError))
849 {
850 PyErr_Clear();
851 Py_INCREF(dflt);
852 result = dflt;
853 }
854 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000855}
856
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000857PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000858"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000859\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000860Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
861When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000862exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000863
864
Guido van Rossum79f25d91997-04-29 20:08:16 +0000865static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000866builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 d = PyEval_GetGlobals();
871 Py_XINCREF(d);
872 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000873}
874
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000875PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000876"globals() -> dictionary\n\
877\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000878Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000879
880
Guido van Rossum79f25d91997-04-29 20:08:16 +0000881static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000882builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 PyObject *v;
885 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
888 return NULL;
889 if (!PyUnicode_Check(name)) {
890 PyErr_SetString(PyExc_TypeError,
891 "hasattr(): attribute name must be string");
892 return NULL;
893 }
894 v = PyObject_GetAttr(v, name);
895 if (v == NULL) {
896 if (!PyErr_ExceptionMatches(PyExc_Exception))
897 return NULL;
898 else {
899 PyErr_Clear();
900 Py_INCREF(Py_False);
901 return Py_False;
902 }
903 }
904 Py_DECREF(v);
905 Py_INCREF(Py_True);
906 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000907}
908
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000909PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000910"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000911\n\
912Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000913(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000914
915
Guido van Rossum79f25d91997-04-29 20:08:16 +0000916static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000917builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000920}
921
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000922PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000923"id(object) -> integer\n\
924\n\
925Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000926simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000927
928
Raymond Hettingera6c60372008-03-13 01:26:19 +0000929/* map object ************************************************************/
930
931typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 PyObject_HEAD
933 PyObject *iters;
934 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000935} mapobject;
936
Guido van Rossum79f25d91997-04-29 20:08:16 +0000937static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000938map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 PyObject *it, *iters, *func;
941 mapobject *lz;
942 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
945 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 numargs = PyTuple_Size(args);
948 if (numargs < 2) {
949 PyErr_SetString(PyExc_TypeError,
950 "map() must have at least two arguments.");
951 return NULL;
952 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 iters = PyTuple_New(numargs-1);
955 if (iters == NULL)
956 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 for (i=1 ; i<numargs ; i++) {
959 /* Get iterator. */
960 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
961 if (it == NULL) {
962 Py_DECREF(iters);
963 return NULL;
964 }
965 PyTuple_SET_ITEM(iters, i-1, it);
966 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 /* create mapobject structure */
969 lz = (mapobject *)type->tp_alloc(type, 0);
970 if (lz == NULL) {
971 Py_DECREF(iters);
972 return NULL;
973 }
974 lz->iters = iters;
975 func = PyTuple_GET_ITEM(args, 0);
976 Py_INCREF(func);
977 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000980}
981
982static void
983map_dealloc(mapobject *lz)
984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 PyObject_GC_UnTrack(lz);
986 Py_XDECREF(lz->iters);
987 Py_XDECREF(lz->func);
988 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +0000989}
990
991static int
992map_traverse(mapobject *lz, visitproc visit, void *arg)
993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 Py_VISIT(lz->iters);
995 Py_VISIT(lz->func);
996 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000997}
998
999static PyObject *
1000map_next(mapobject *lz)
1001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 PyObject *val;
1003 PyObject *argtuple;
1004 PyObject *result;
1005 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 numargs = PyTuple_Size(lz->iters);
1008 argtuple = PyTuple_New(numargs);
1009 if (argtuple == NULL)
1010 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 for (i=0 ; i<numargs ; i++) {
1013 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1014 if (val == NULL) {
1015 Py_DECREF(argtuple);
1016 return NULL;
1017 }
1018 PyTuple_SET_ITEM(argtuple, i, val);
1019 }
1020 result = PyObject_Call(lz->func, argtuple, NULL);
1021 Py_DECREF(argtuple);
1022 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001023}
1024
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001025PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001026"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001027\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001028Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001030
Raymond Hettingera6c60372008-03-13 01:26:19 +00001031PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1033 "map", /* tp_name */
1034 sizeof(mapobject), /* tp_basicsize */
1035 0, /* tp_itemsize */
1036 /* methods */
1037 (destructor)map_dealloc, /* tp_dealloc */
1038 0, /* tp_print */
1039 0, /* tp_getattr */
1040 0, /* tp_setattr */
1041 0, /* tp_reserved */
1042 0, /* tp_repr */
1043 0, /* tp_as_number */
1044 0, /* tp_as_sequence */
1045 0, /* tp_as_mapping */
1046 0, /* tp_hash */
1047 0, /* tp_call */
1048 0, /* tp_str */
1049 PyObject_GenericGetAttr, /* tp_getattro */
1050 0, /* tp_setattro */
1051 0, /* tp_as_buffer */
1052 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1053 Py_TPFLAGS_BASETYPE, /* tp_flags */
1054 map_doc, /* tp_doc */
1055 (traverseproc)map_traverse, /* tp_traverse */
1056 0, /* tp_clear */
1057 0, /* tp_richcompare */
1058 0, /* tp_weaklistoffset */
1059 PyObject_SelfIter, /* tp_iter */
1060 (iternextfunc)map_next, /* tp_iternext */
1061 0, /* tp_methods */
1062 0, /* tp_members */
1063 0, /* tp_getset */
1064 0, /* tp_base */
1065 0, /* tp_dict */
1066 0, /* tp_descr_get */
1067 0, /* tp_descr_set */
1068 0, /* tp_dictoffset */
1069 0, /* tp_init */
1070 PyType_GenericAlloc, /* tp_alloc */
1071 map_new, /* tp_new */
1072 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001073};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001074
Guido van Rossum79f25d91997-04-29 20:08:16 +00001075static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001076builtin_next(PyObject *self, PyObject *args)
1077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 PyObject *it, *res;
1079 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1082 return NULL;
1083 if (!PyIter_Check(it)) {
1084 PyErr_Format(PyExc_TypeError,
1085 "%.200s object is not an iterator",
1086 it->ob_type->tp_name);
1087 return NULL;
1088 }
1089
1090 res = (*it->ob_type->tp_iternext)(it);
1091 if (res != NULL) {
1092 return res;
1093 } else if (def != NULL) {
1094 if (PyErr_Occurred()) {
1095 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1096 return NULL;
1097 PyErr_Clear();
1098 }
1099 Py_INCREF(def);
1100 return def;
1101 } else if (PyErr_Occurred()) {
1102 return NULL;
1103 } else {
1104 PyErr_SetNone(PyExc_StopIteration);
1105 return NULL;
1106 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001107}
1108
1109PyDoc_STRVAR(next_doc,
1110"next(iterator[, default])\n\
1111\n\
1112Return the next item from the iterator. If default is given and the iterator\n\
1113is exhausted, it is returned instead of raising StopIteration.");
1114
1115
1116static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001117builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 PyObject *v;
1120 PyObject *name;
1121 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1124 return NULL;
1125 if (PyObject_SetAttr(v, name, value) != 0)
1126 return NULL;
1127 Py_INCREF(Py_None);
1128 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001129}
1130
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001131PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001132"setattr(object, name, value)\n\
1133\n\
1134Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001135``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001136
1137
Guido van Rossum79f25d91997-04-29 20:08:16 +00001138static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001139builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 PyObject *v;
1142 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1145 return NULL;
1146 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1147 return NULL;
1148 Py_INCREF(Py_None);
1149 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001150}
1151
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001152PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001153"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001154\n\
1155Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001156``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001157
1158
Guido van Rossum79f25d91997-04-29 20:08:16 +00001159static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001160builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 x = PyObject_Hash(v);
1165 if (x == -1)
1166 return NULL;
1167 return PyLong_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001168}
1169
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001170PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001171"hash(object) -> integer\n\
1172\n\
1173Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001174the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001175
1176
Guido van Rossum79f25d91997-04-29 20:08:16 +00001177static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001178builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001181}
1182
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001183PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001184"hex(number) -> string\n\
1185\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001186Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001187
1188
Guido van Rossum79f25d91997-04-29 20:08:16 +00001189static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001190builtin_iter(PyObject *self, PyObject *args)
1191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1195 return NULL;
1196 if (w == NULL)
1197 return PyObject_GetIter(v);
1198 if (!PyCallable_Check(v)) {
1199 PyErr_SetString(PyExc_TypeError,
1200 "iter(v, w): v must be callable");
1201 return NULL;
1202 }
1203 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001204}
1205
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001206PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001207"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001208iter(callable, sentinel) -> iterator\n\
1209\n\
1210Get an iterator from an object. In the first form, the argument must\n\
1211supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001212In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001213
1214
1215static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001216builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 res = PyObject_Size(v);
1221 if (res < 0 && PyErr_Occurred())
1222 return NULL;
1223 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001224}
1225
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001226PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001227"len(object) -> integer\n\
1228\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001229Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001230
1231
Guido van Rossum79f25d91997-04-29 20:08:16 +00001232static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001233builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 d = PyEval_GetLocals();
1238 Py_XINCREF(d);
1239 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001240}
1241
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001242PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001243"locals() -> dictionary\n\
1244\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001245Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001246
1247
Guido van Rossum79f25d91997-04-29 20:08:16 +00001248static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001249min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1252 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 if (PyTuple_Size(args) > 1)
1255 v = args;
1256 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1257 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1260 keyfunc = PyDict_GetItemString(kwds, "key");
1261 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1262 PyErr_Format(PyExc_TypeError,
1263 "%s() got an unexpected keyword argument", name);
1264 return NULL;
1265 }
1266 Py_INCREF(keyfunc);
1267 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 it = PyObject_GetIter(v);
1270 if (it == NULL) {
1271 Py_XDECREF(keyfunc);
1272 return NULL;
1273 }
Tim Petersc3074532001-05-03 07:00:32 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 maxitem = NULL; /* the result */
1276 maxval = NULL; /* the value associated with the result */
1277 while (( item = PyIter_Next(it) )) {
1278 /* get the value from the key function */
1279 if (keyfunc != NULL) {
1280 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1281 if (val == NULL)
1282 goto Fail_it_item;
1283 }
1284 /* no key function; the value is the item */
1285 else {
1286 val = item;
1287 Py_INCREF(val);
1288 }
Tim Petersc3074532001-05-03 07:00:32 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 /* maximum value and item are unset; set them */
1291 if (maxval == NULL) {
1292 maxitem = item;
1293 maxval = val;
1294 }
1295 /* maximum value and item are set; update them as necessary */
1296 else {
1297 int cmp = PyObject_RichCompareBool(val, maxval, op);
1298 if (cmp < 0)
1299 goto Fail_it_item_and_val;
1300 else if (cmp > 0) {
1301 Py_DECREF(maxval);
1302 Py_DECREF(maxitem);
1303 maxval = val;
1304 maxitem = item;
1305 }
1306 else {
1307 Py_DECREF(item);
1308 Py_DECREF(val);
1309 }
1310 }
1311 }
1312 if (PyErr_Occurred())
1313 goto Fail_it;
1314 if (maxval == NULL) {
1315 PyErr_Format(PyExc_ValueError,
1316 "%s() arg is an empty sequence", name);
1317 assert(maxitem == NULL);
1318 }
1319 else
1320 Py_DECREF(maxval);
1321 Py_DECREF(it);
1322 Py_XDECREF(keyfunc);
1323 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001324
1325Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001327Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001329Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 Py_XDECREF(maxval);
1331 Py_XDECREF(maxitem);
1332 Py_DECREF(it);
1333 Py_XDECREF(keyfunc);
1334 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001335}
1336
Guido van Rossum79f25d91997-04-29 20:08:16 +00001337static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001338builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001341}
1342
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001343PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001344"min(iterable[, key=func]) -> value\n\
1345min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001346\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001347With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001348With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001349
1350
Guido van Rossum79f25d91997-04-29 20:08:16 +00001351static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001352builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001355}
1356
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001357PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001358"max(iterable[, key=func]) -> value\n\
1359max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001360\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001361With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001362With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001363
1364
Guido van Rossum79f25d91997-04-29 20:08:16 +00001365static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001366builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001369}
1370
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001371PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001372"oct(number) -> string\n\
1373\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001374Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001375
1376
Guido van Rossum79f25d91997-04-29 20:08:16 +00001377static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001378builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 long ord;
1381 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 if (PyBytes_Check(obj)) {
1384 size = PyBytes_GET_SIZE(obj);
1385 if (size == 1) {
1386 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1387 return PyLong_FromLong(ord);
1388 }
1389 }
1390 else if (PyUnicode_Check(obj)) {
1391 size = PyUnicode_GET_SIZE(obj);
1392 if (size == 1) {
1393 ord = (long)*PyUnicode_AS_UNICODE(obj);
1394 return PyLong_FromLong(ord);
1395 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001396#ifndef Py_UNICODE_WIDE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 if (size == 2) {
1398 /* Decode a valid surrogate pair */
1399 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1400 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1401 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1402 0xDC00 <= c1 && c1 <= 0xDFFF) {
1403 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1404 0x00010000);
1405 return PyLong_FromLong(ord);
1406 }
1407 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001408#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 }
1410 else if (PyByteArray_Check(obj)) {
1411 /* XXX Hopefully this is temporary */
1412 size = PyByteArray_GET_SIZE(obj);
1413 if (size == 1) {
1414 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1415 return PyLong_FromLong(ord);
1416 }
1417 }
1418 else {
1419 PyErr_Format(PyExc_TypeError,
1420 "ord() expected string of length 1, but " \
1421 "%.200s found", obj->ob_type->tp_name);
1422 return NULL;
1423 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 PyErr_Format(PyExc_TypeError,
1426 "ord() expected a character, "
1427 "but string of length %zd found",
1428 size);
1429 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001430}
1431
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001432PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001433"ord(c) -> integer\n\
1434\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001435Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001436)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001437#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001438PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001439"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001440)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001441#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001442;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001443
1444
Guido van Rossum79f25d91997-04-29 20:08:16 +00001445static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001446builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1451 return NULL;
1452 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001453}
1454
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001455PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001456"pow(x, y[, z]) -> number\n\
1457\n\
1458With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001459equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001460
1461
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001462
Guido van Rossum34343512006-11-30 22:13:52 +00001463static PyObject *
1464builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 static char *kwlist[] = {"sep", "end", "file", 0};
1467 static PyObject *dummy_args;
1468 PyObject *sep = NULL, *end = NULL, *file = NULL;
1469 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 if (dummy_args == NULL) {
1472 if (!(dummy_args = PyTuple_New(0)))
1473 return NULL;
1474 }
1475 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1476 kwlist, &sep, &end, &file))
1477 return NULL;
1478 if (file == NULL || file == Py_None) {
1479 file = PySys_GetObject("stdout");
1480 /* sys.stdout may be None when FILE* stdout isn't connected */
1481 if (file == Py_None)
1482 Py_RETURN_NONE;
1483 }
Guido van Rossum34343512006-11-30 22:13:52 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 if (sep == Py_None) {
1486 sep = NULL;
1487 }
1488 else if (sep && !PyUnicode_Check(sep)) {
1489 PyErr_Format(PyExc_TypeError,
1490 "sep must be None or a string, not %.200s",
1491 sep->ob_type->tp_name);
1492 return NULL;
1493 }
1494 if (end == Py_None) {
1495 end = NULL;
1496 }
1497 else if (end && !PyUnicode_Check(end)) {
1498 PyErr_Format(PyExc_TypeError,
1499 "end must be None or a string, not %.200s",
1500 end->ob_type->tp_name);
1501 return NULL;
1502 }
Guido van Rossum34343512006-11-30 22:13:52 +00001503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 for (i = 0; i < PyTuple_Size(args); i++) {
1505 if (i > 0) {
1506 if (sep == NULL)
1507 err = PyFile_WriteString(" ", file);
1508 else
1509 err = PyFile_WriteObject(sep, file,
1510 Py_PRINT_RAW);
1511 if (err)
1512 return NULL;
1513 }
1514 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1515 Py_PRINT_RAW);
1516 if (err)
1517 return NULL;
1518 }
Guido van Rossum34343512006-11-30 22:13:52 +00001519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 if (end == NULL)
1521 err = PyFile_WriteString("\n", file);
1522 else
1523 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1524 if (err)
1525 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001528}
1529
1530PyDoc_STRVAR(print_doc,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001531"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001532\n\
1533Prints the values to a stream, or to sys.stdout by default.\n\
1534Optional keyword arguments:\n\
1535file: a file-like object (stream); defaults to the current sys.stdout.\n\
1536sep: string inserted between values, default a space.\n\
1537end: string appended after the last value, default a newline.");
1538
1539
Guido van Rossuma88a0332007-02-26 16:59:55 +00001540static PyObject *
1541builtin_input(PyObject *self, PyObject *args)
1542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 PyObject *promptarg = NULL;
1544 PyObject *fin = PySys_GetObject("stdin");
1545 PyObject *fout = PySys_GetObject("stdout");
1546 PyObject *ferr = PySys_GetObject("stderr");
1547 PyObject *tmp;
1548 long fd;
1549 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 /* Parse arguments */
1552 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1553 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 /* Check that stdin/out/err are intact */
1556 if (fin == NULL || fin == Py_None) {
1557 PyErr_SetString(PyExc_RuntimeError,
1558 "input(): lost sys.stdin");
1559 return NULL;
1560 }
1561 if (fout == NULL || fout == Py_None) {
1562 PyErr_SetString(PyExc_RuntimeError,
1563 "input(): lost sys.stdout");
1564 return NULL;
1565 }
1566 if (ferr == NULL || ferr == Py_None) {
1567 PyErr_SetString(PyExc_RuntimeError,
1568 "input(): lost sys.stderr");
1569 return NULL;
1570 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 /* First of all, flush stderr */
1573 tmp = PyObject_CallMethod(ferr, "flush", "");
1574 if (tmp == NULL)
1575 PyErr_Clear();
1576 else
1577 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 /* We should only use (GNU) readline if Python's sys.stdin and
1580 sys.stdout are the same as C's stdin and stdout, because we
1581 need to pass it those. */
1582 tmp = PyObject_CallMethod(fin, "fileno", "");
1583 if (tmp == NULL) {
1584 PyErr_Clear();
1585 tty = 0;
1586 }
1587 else {
1588 fd = PyLong_AsLong(tmp);
1589 Py_DECREF(tmp);
1590 if (fd < 0 && PyErr_Occurred())
1591 return NULL;
1592 tty = fd == fileno(stdin) && isatty(fd);
1593 }
1594 if (tty) {
1595 tmp = PyObject_CallMethod(fout, "fileno", "");
1596 if (tmp == NULL)
1597 PyErr_Clear();
1598 else {
1599 fd = PyLong_AsLong(tmp);
1600 Py_DECREF(tmp);
1601 if (fd < 0 && PyErr_Occurred())
1602 return NULL;
1603 tty = fd == fileno(stdout) && isatty(fd);
1604 }
1605 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 /* If we're interactive, use (GNU) readline */
1608 if (tty) {
1609 PyObject *po;
1610 char *prompt;
1611 char *s;
1612 PyObject *stdin_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001613 char *stdin_encoding_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 PyObject *result;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1617 if (!stdin_encoding)
1618 /* stdin is a text stream, so it must have an
1619 encoding. */
1620 return NULL;
Victor Stinner306f0102010-05-19 01:06:22 +00001621 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
1622 if (stdin_encoding_str == NULL) {
1623 Py_DECREF(stdin_encoding);
1624 return NULL;
1625 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 tmp = PyObject_CallMethod(fout, "flush", "");
1627 if (tmp == NULL)
1628 PyErr_Clear();
1629 else
1630 Py_DECREF(tmp);
1631 if (promptarg != NULL) {
1632 PyObject *stringpo;
1633 PyObject *stdout_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001634 char *stdout_encoding_str;
1635 stdout_encoding = PyObject_GetAttrString(fout, "encoding");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 if (stdout_encoding == NULL) {
1637 Py_DECREF(stdin_encoding);
1638 return NULL;
1639 }
Victor Stinner306f0102010-05-19 01:06:22 +00001640 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
1641 if (stdout_encoding_str == NULL) {
1642 Py_DECREF(stdin_encoding);
1643 Py_DECREF(stdout_encoding);
1644 return NULL;
1645 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 stringpo = PyObject_Str(promptarg);
1647 if (stringpo == NULL) {
1648 Py_DECREF(stdin_encoding);
1649 Py_DECREF(stdout_encoding);
1650 return NULL;
1651 }
1652 po = PyUnicode_AsEncodedString(stringpo,
Victor Stinner306f0102010-05-19 01:06:22 +00001653 stdout_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 Py_DECREF(stdout_encoding);
1655 Py_DECREF(stringpo);
1656 if (po == NULL) {
1657 Py_DECREF(stdin_encoding);
1658 return NULL;
1659 }
1660 prompt = PyBytes_AsString(po);
1661 if (prompt == NULL) {
1662 Py_DECREF(stdin_encoding);
1663 Py_DECREF(po);
1664 return NULL;
1665 }
1666 }
1667 else {
1668 po = NULL;
1669 prompt = "";
1670 }
1671 s = PyOS_Readline(stdin, stdout, prompt);
1672 Py_XDECREF(po);
1673 if (s == NULL) {
1674 if (!PyErr_Occurred())
1675 PyErr_SetNone(PyExc_KeyboardInterrupt);
1676 Py_DECREF(stdin_encoding);
1677 return NULL;
1678 }
1679 if (*s == '\0') {
1680 PyErr_SetNone(PyExc_EOFError);
1681 result = NULL;
1682 }
1683 else { /* strip trailing '\n' */
1684 size_t len = strlen(s);
1685 if (len > PY_SSIZE_T_MAX) {
1686 PyErr_SetString(PyExc_OverflowError,
1687 "input: input too long");
1688 result = NULL;
1689 }
1690 else {
Victor Stinner306f0102010-05-19 01:06:22 +00001691 result = PyUnicode_Decode(s, len-1, stdin_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 }
1693 }
1694 Py_DECREF(stdin_encoding);
1695 PyMem_FREE(s);
1696 return result;
1697 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 /* Fallback if we're not interactive */
1700 if (promptarg != NULL) {
1701 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1702 return NULL;
1703 }
1704 tmp = PyObject_CallMethod(fout, "flush", "");
1705 if (tmp == NULL)
1706 PyErr_Clear();
1707 else
1708 Py_DECREF(tmp);
1709 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001710}
1711
1712PyDoc_STRVAR(input_doc,
1713"input([prompt]) -> string\n\
1714\n\
1715Read a string from standard input. The trailing newline is stripped.\n\
1716If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1717On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1718is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001719
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001720
Guido van Rossum79f25d91997-04-29 20:08:16 +00001721static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001722builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001725}
1726
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001727PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001728"repr(object) -> string\n\
1729\n\
1730Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001731For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001732
1733
Guido van Rossum79f25d91997-04-29 20:08:16 +00001734static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001735builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 static PyObject *round_str = NULL;
1738 PyObject *ndigits = NULL;
1739 static char *kwlist[] = {"number", "ndigits", 0};
1740 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1743 kwlist, &number, &ndigits))
1744 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 if (Py_TYPE(number)->tp_dict == NULL) {
1747 if (PyType_Ready(Py_TYPE(number)) < 0)
1748 return NULL;
1749 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 if (round_str == NULL) {
1752 round_str = PyUnicode_InternFromString("__round__");
1753 if (round_str == NULL)
1754 return NULL;
1755 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 round = _PyType_Lookup(Py_TYPE(number), round_str);
1758 if (round == NULL) {
1759 PyErr_Format(PyExc_TypeError,
1760 "type %.100s doesn't define __round__ method",
1761 Py_TYPE(number)->tp_name);
1762 return NULL;
1763 }
Alex Martelliae211f92007-08-22 23:21:33 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 if (ndigits == NULL)
1766 return PyObject_CallFunction(round, "O", number);
1767 else
1768 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001769}
1770
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001771PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001772"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001773\n\
1774Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001775This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001776same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001777
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001778
Raymond Hettinger64958a12003-12-17 20:43:33 +00001779static PyObject *
1780builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1783 PyObject *callable;
1784 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1785 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 /* args 1-3 should match listsort in Objects/listobject.c */
1788 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1789 kwlist, &seq, &keyfunc, &reverse))
1790 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 newlist = PySequence_List(seq);
1793 if (newlist == NULL)
1794 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 callable = PyObject_GetAttrString(newlist, "sort");
1797 if (callable == NULL) {
1798 Py_DECREF(newlist);
1799 return NULL;
1800 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 newargs = PyTuple_GetSlice(args, 1, 4);
1803 if (newargs == NULL) {
1804 Py_DECREF(newlist);
1805 Py_DECREF(callable);
1806 return NULL;
1807 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 v = PyObject_Call(callable, newargs, kwds);
1810 Py_DECREF(newargs);
1811 Py_DECREF(callable);
1812 if (v == NULL) {
1813 Py_DECREF(newlist);
1814 return NULL;
1815 }
1816 Py_DECREF(v);
1817 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001818}
1819
1820PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001821"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001822
Guido van Rossum79f25d91997-04-29 20:08:16 +00001823static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001824builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 PyObject *v = NULL;
1827 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1830 return NULL;
1831 if (v == NULL) {
1832 d = PyEval_GetLocals();
1833 if (d == NULL) {
1834 if (!PyErr_Occurred())
1835 PyErr_SetString(PyExc_SystemError,
1836 "vars(): no locals!?");
1837 }
1838 else
1839 Py_INCREF(d);
1840 }
1841 else {
1842 d = PyObject_GetAttrString(v, "__dict__");
1843 if (d == NULL) {
1844 PyErr_SetString(PyExc_TypeError,
1845 "vars() argument must have __dict__ attribute");
1846 return NULL;
1847 }
1848 }
1849 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001850}
1851
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001852PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001853"vars([object]) -> dictionary\n\
1854\n\
1855Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001856With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001857
Alex Martellia70b1912003-04-22 08:12:33 +00001858static PyObject*
1859builtin_sum(PyObject *self, PyObject *args)
1860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 PyObject *seq;
1862 PyObject *result = NULL;
1863 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1866 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 iter = PyObject_GetIter(seq);
1869 if (iter == NULL)
1870 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 if (result == NULL) {
1873 result = PyLong_FromLong(0);
1874 if (result == NULL) {
1875 Py_DECREF(iter);
1876 return NULL;
1877 }
1878 } else {
1879 /* reject string values for 'start' parameter */
1880 if (PyUnicode_Check(result)) {
1881 PyErr_SetString(PyExc_TypeError,
1882 "sum() can't sum strings [use ''.join(seq) instead]");
1883 Py_DECREF(iter);
1884 return NULL;
1885 }
1886 if (PyByteArray_Check(result)) {
1887 PyErr_SetString(PyExc_TypeError,
1888 "sum() can't sum bytes [use b''.join(seq) instead]");
1889 Py_DECREF(iter);
1890 return NULL;
1891 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 Py_INCREF(result);
1894 }
Alex Martellia70b1912003-04-22 08:12:33 +00001895
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001896#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1898 Assumes all inputs are the same type. If the assumption fails, default
1899 to the more general routine.
1900 */
1901 if (PyLong_CheckExact(result)) {
1902 int overflow;
1903 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1904 /* If this already overflowed, don't even enter the loop. */
1905 if (overflow == 0) {
1906 Py_DECREF(result);
1907 result = NULL;
1908 }
1909 while(result == NULL) {
1910 item = PyIter_Next(iter);
1911 if (item == NULL) {
1912 Py_DECREF(iter);
1913 if (PyErr_Occurred())
1914 return NULL;
1915 return PyLong_FromLong(i_result);
1916 }
1917 if (PyLong_CheckExact(item)) {
1918 long b = PyLong_AsLongAndOverflow(item, &overflow);
1919 long x = i_result + b;
1920 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1921 i_result = x;
1922 Py_DECREF(item);
1923 continue;
1924 }
1925 }
1926 /* Either overflowed or is not an int. Restore real objects and process normally */
1927 result = PyLong_FromLong(i_result);
1928 temp = PyNumber_Add(result, item);
1929 Py_DECREF(result);
1930 Py_DECREF(item);
1931 result = temp;
1932 if (result == NULL) {
1933 Py_DECREF(iter);
1934 return NULL;
1935 }
1936 }
1937 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 if (PyFloat_CheckExact(result)) {
1940 double f_result = PyFloat_AS_DOUBLE(result);
1941 Py_DECREF(result);
1942 result = NULL;
1943 while(result == NULL) {
1944 item = PyIter_Next(iter);
1945 if (item == NULL) {
1946 Py_DECREF(iter);
1947 if (PyErr_Occurred())
1948 return NULL;
1949 return PyFloat_FromDouble(f_result);
1950 }
1951 if (PyFloat_CheckExact(item)) {
1952 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1953 f_result += PyFloat_AS_DOUBLE(item);
1954 PyFPE_END_PROTECT(f_result)
1955 Py_DECREF(item);
1956 continue;
1957 }
1958 if (PyLong_CheckExact(item)) {
1959 long value;
1960 int overflow;
1961 value = PyLong_AsLongAndOverflow(item, &overflow);
1962 if (!overflow) {
1963 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1964 f_result += (double)value;
1965 PyFPE_END_PROTECT(f_result)
1966 Py_DECREF(item);
1967 continue;
1968 }
1969 }
1970 result = PyFloat_FromDouble(f_result);
1971 temp = PyNumber_Add(result, item);
1972 Py_DECREF(result);
1973 Py_DECREF(item);
1974 result = temp;
1975 if (result == NULL) {
1976 Py_DECREF(iter);
1977 return NULL;
1978 }
1979 }
1980 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001981#endif
1982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 for(;;) {
1984 item = PyIter_Next(iter);
1985 if (item == NULL) {
1986 /* error, or end-of-sequence */
1987 if (PyErr_Occurred()) {
1988 Py_DECREF(result);
1989 result = NULL;
1990 }
1991 break;
1992 }
1993 /* It's tempting to use PyNumber_InPlaceAdd instead of
1994 PyNumber_Add here, to avoid quadratic running time
1995 when doing 'sum(list_of_lists, [])'. However, this
1996 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 empty = []
1999 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 would change the value of empty. */
2002 temp = PyNumber_Add(result, item);
2003 Py_DECREF(result);
2004 Py_DECREF(item);
2005 result = temp;
2006 if (result == NULL)
2007 break;
2008 }
2009 Py_DECREF(iter);
2010 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002011}
2012
2013PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002014"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002015\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002016Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2017of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002018empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002019
2020
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002021static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002022builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 PyObject *inst;
2025 PyObject *cls;
2026 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2029 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 retval = PyObject_IsInstance(inst, cls);
2032 if (retval < 0)
2033 return NULL;
2034 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002035}
2036
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002037PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002038"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002039\n\
2040Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002041With a type as second argument, return whether that is the object's type.\n\
2042The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002043isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002044
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002045
2046static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002047builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 PyObject *derived;
2050 PyObject *cls;
2051 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2054 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 retval = PyObject_IsSubclass(derived, cls);
2057 if (retval < 0)
2058 return NULL;
2059 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002060}
2061
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002062PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002063"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002064\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002065Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2066When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2067is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002068
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002069
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002070typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 PyObject_HEAD
2072 Py_ssize_t tuplesize;
2073 PyObject *ittuple; /* tuple of iterators */
2074 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002075} zipobject;
2076
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002077static PyObject *
2078zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 zipobject *lz;
2081 Py_ssize_t i;
2082 PyObject *ittuple; /* tuple of iterators */
2083 PyObject *result;
2084 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2087 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 /* args must be a tuple */
2090 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 /* obtain iterators */
2093 ittuple = PyTuple_New(tuplesize);
2094 if (ittuple == NULL)
2095 return NULL;
2096 for (i=0; i < tuplesize; ++i) {
2097 PyObject *item = PyTuple_GET_ITEM(args, i);
2098 PyObject *it = PyObject_GetIter(item);
2099 if (it == NULL) {
2100 if (PyErr_ExceptionMatches(PyExc_TypeError))
2101 PyErr_Format(PyExc_TypeError,
2102 "zip argument #%zd must support iteration",
2103 i+1);
2104 Py_DECREF(ittuple);
2105 return NULL;
2106 }
2107 PyTuple_SET_ITEM(ittuple, i, it);
2108 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 /* create a result holder */
2111 result = PyTuple_New(tuplesize);
2112 if (result == NULL) {
2113 Py_DECREF(ittuple);
2114 return NULL;
2115 }
2116 for (i=0 ; i < tuplesize ; i++) {
2117 Py_INCREF(Py_None);
2118 PyTuple_SET_ITEM(result, i, Py_None);
2119 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 /* create zipobject structure */
2122 lz = (zipobject *)type->tp_alloc(type, 0);
2123 if (lz == NULL) {
2124 Py_DECREF(ittuple);
2125 Py_DECREF(result);
2126 return NULL;
2127 }
2128 lz->ittuple = ittuple;
2129 lz->tuplesize = tuplesize;
2130 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002133}
2134
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002135static void
2136zip_dealloc(zipobject *lz)
2137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 PyObject_GC_UnTrack(lz);
2139 Py_XDECREF(lz->ittuple);
2140 Py_XDECREF(lz->result);
2141 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002142}
2143
2144static int
2145zip_traverse(zipobject *lz, visitproc visit, void *arg)
2146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 Py_VISIT(lz->ittuple);
2148 Py_VISIT(lz->result);
2149 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002150}
2151
2152static PyObject *
2153zip_next(zipobject *lz)
2154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 Py_ssize_t i;
2156 Py_ssize_t tuplesize = lz->tuplesize;
2157 PyObject *result = lz->result;
2158 PyObject *it;
2159 PyObject *item;
2160 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 if (tuplesize == 0)
2163 return NULL;
2164 if (Py_REFCNT(result) == 1) {
2165 Py_INCREF(result);
2166 for (i=0 ; i < tuplesize ; i++) {
2167 it = PyTuple_GET_ITEM(lz->ittuple, i);
2168 item = (*Py_TYPE(it)->tp_iternext)(it);
2169 if (item == NULL) {
2170 Py_DECREF(result);
2171 return NULL;
2172 }
2173 olditem = PyTuple_GET_ITEM(result, i);
2174 PyTuple_SET_ITEM(result, i, item);
2175 Py_DECREF(olditem);
2176 }
2177 } else {
2178 result = PyTuple_New(tuplesize);
2179 if (result == NULL)
2180 return NULL;
2181 for (i=0 ; i < tuplesize ; i++) {
2182 it = PyTuple_GET_ITEM(lz->ittuple, i);
2183 item = (*Py_TYPE(it)->tp_iternext)(it);
2184 if (item == NULL) {
2185 Py_DECREF(result);
2186 return NULL;
2187 }
2188 PyTuple_SET_ITEM(result, i, item);
2189 }
2190 }
2191 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002192}
Barry Warsawbd599b52000-08-03 15:45:29 +00002193
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002194PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002195"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002196\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002197Return a zip object whose .__next__() method returns a tuple where\n\
2198the i-th element comes from the i-th iterable argument. The .__next__()\n\
2199method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002200is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002201
2202PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2204 "zip", /* tp_name */
2205 sizeof(zipobject), /* tp_basicsize */
2206 0, /* tp_itemsize */
2207 /* methods */
2208 (destructor)zip_dealloc, /* tp_dealloc */
2209 0, /* tp_print */
2210 0, /* tp_getattr */
2211 0, /* tp_setattr */
2212 0, /* tp_reserved */
2213 0, /* tp_repr */
2214 0, /* tp_as_number */
2215 0, /* tp_as_sequence */
2216 0, /* tp_as_mapping */
2217 0, /* tp_hash */
2218 0, /* tp_call */
2219 0, /* tp_str */
2220 PyObject_GenericGetAttr, /* tp_getattro */
2221 0, /* tp_setattro */
2222 0, /* tp_as_buffer */
2223 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2224 Py_TPFLAGS_BASETYPE, /* tp_flags */
2225 zip_doc, /* tp_doc */
2226 (traverseproc)zip_traverse, /* tp_traverse */
2227 0, /* tp_clear */
2228 0, /* tp_richcompare */
2229 0, /* tp_weaklistoffset */
2230 PyObject_SelfIter, /* tp_iter */
2231 (iternextfunc)zip_next, /* tp_iternext */
2232 0, /* tp_methods */
2233 0, /* tp_members */
2234 0, /* tp_getset */
2235 0, /* tp_base */
2236 0, /* tp_dict */
2237 0, /* tp_descr_get */
2238 0, /* tp_descr_set */
2239 0, /* tp_dictoffset */
2240 0, /* tp_init */
2241 PyType_GenericAlloc, /* tp_alloc */
2242 zip_new, /* tp_new */
2243 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002244};
Barry Warsawbd599b52000-08-03 15:45:29 +00002245
2246
Guido van Rossum79f25d91997-04-29 20:08:16 +00002247static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 {"__build_class__", (PyCFunction)builtin___build_class__,
2249 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2250 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2251 {"abs", builtin_abs, METH_O, abs_doc},
2252 {"all", builtin_all, METH_O, all_doc},
2253 {"any", builtin_any, METH_O, any_doc},
2254 {"ascii", builtin_ascii, METH_O, ascii_doc},
2255 {"bin", builtin_bin, METH_O, bin_doc},
2256 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2257 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2258 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2259 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2260 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2261 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2262 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2263 {"format", builtin_format, METH_VARARGS, format_doc},
2264 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2265 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2266 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2267 {"hash", builtin_hash, METH_O, hash_doc},
2268 {"hex", builtin_hex, METH_O, hex_doc},
2269 {"id", builtin_id, METH_O, id_doc},
2270 {"input", builtin_input, METH_VARARGS, input_doc},
2271 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2272 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2273 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2274 {"len", builtin_len, METH_O, len_doc},
2275 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2276 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2277 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2278 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2279 {"oct", builtin_oct, METH_O, oct_doc},
2280 {"ord", builtin_ord, METH_O, ord_doc},
2281 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2282 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2283 {"repr", builtin_repr, METH_O, repr_doc},
2284 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2285 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2286 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2287 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2288 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2289 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002290};
2291
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002292PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002293"Built-in functions, exceptions, and other objects.\n\
2294\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002295Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002296
Martin v. Löwis1a214512008-06-11 05:26:20 +00002297static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 PyModuleDef_HEAD_INIT,
2299 "builtins",
2300 builtin_doc,
2301 -1, /* multiple "initialization" just copies the module dict. */
2302 builtin_methods,
2303 NULL,
2304 NULL,
2305 NULL,
2306 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002307};
2308
2309
Guido van Rossum25ce5661997-08-02 03:10:38 +00002310PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002311_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 PyObject *mod, *dict, *debug;
2314 mod = PyModule_Create(&builtinsmodule);
2315 if (mod == NULL)
2316 return NULL;
2317 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002318
Tim Peters7571a0f2003-03-23 17:52:28 +00002319#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 /* "builtins" exposes a number of statically allocated objects
2321 * that, before this code was added in 2.3, never showed up in
2322 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2323 * result, programs leaking references to None and False (etc)
2324 * couldn't be diagnosed by examining sys.getobjects(0).
2325 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002326#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2327#else
2328#define ADD_TO_ALL(OBJECT) (void)0
2329#endif
2330
Tim Peters4b7625e2001-09-13 21:37:17 +00002331#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2333 return NULL; \
2334 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 SETBUILTIN("None", Py_None);
2337 SETBUILTIN("Ellipsis", Py_Ellipsis);
2338 SETBUILTIN("NotImplemented", Py_NotImplemented);
2339 SETBUILTIN("False", Py_False);
2340 SETBUILTIN("True", Py_True);
2341 SETBUILTIN("bool", &PyBool_Type);
2342 SETBUILTIN("memoryview", &PyMemoryView_Type);
2343 SETBUILTIN("bytearray", &PyByteArray_Type);
2344 SETBUILTIN("bytes", &PyBytes_Type);
2345 SETBUILTIN("classmethod", &PyClassMethod_Type);
2346 SETBUILTIN("complex", &PyComplex_Type);
2347 SETBUILTIN("dict", &PyDict_Type);
2348 SETBUILTIN("enumerate", &PyEnum_Type);
2349 SETBUILTIN("filter", &PyFilter_Type);
2350 SETBUILTIN("float", &PyFloat_Type);
2351 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2352 SETBUILTIN("property", &PyProperty_Type);
2353 SETBUILTIN("int", &PyLong_Type);
2354 SETBUILTIN("list", &PyList_Type);
2355 SETBUILTIN("map", &PyMap_Type);
2356 SETBUILTIN("object", &PyBaseObject_Type);
2357 SETBUILTIN("range", &PyRange_Type);
2358 SETBUILTIN("reversed", &PyReversed_Type);
2359 SETBUILTIN("set", &PySet_Type);
2360 SETBUILTIN("slice", &PySlice_Type);
2361 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2362 SETBUILTIN("str", &PyUnicode_Type);
2363 SETBUILTIN("super", &PySuper_Type);
2364 SETBUILTIN("tuple", &PyTuple_Type);
2365 SETBUILTIN("type", &PyType_Type);
2366 SETBUILTIN("zip", &PyZip_Type);
2367 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2368 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2369 Py_XDECREF(debug);
2370 return NULL;
2371 }
2372 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002375#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002376#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002377}