blob: 2e8d6e21b3fbb389127667962a90ab03058ce1ac [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum5b722181993-03-30 17:46:03 +00008#include "eval.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00009
Guido van Rossum6bf62da1997-04-11 20:37:35 +000010#include <ctype.h>
11
Victor Stinnerb744ba12010-05-15 12:27:16 +000012#ifdef HAVE_LANGINFO_H
13#include <langinfo.h> /* CODESET */
14#endif
15
Mark Hammond26cffde42001-05-14 12:17:34 +000016/* The default encoding used by the platform file system APIs
17 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000018
19 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
20 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000021*/
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000022#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Mark Hammond26cffde42001-05-14 12:17:34 +000023const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000024int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000025#elif defined(__APPLE__)
26const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000027int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerb744ba12010-05-15 12:27:16 +000028#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
29const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000030int Py_HasFileSystemDefaultEncoding = 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +000031#else
32const char *Py_FileSystemDefaultEncoding = "utf-8";
33int Py_HasFileSystemDefaultEncoding = 1;
Mark Hammond26cffde42001-05-14 12:17:34 +000034#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000035
Guido van Rossum79f25d91997-04-29 20:08:16 +000036static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000037builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
38{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell;
40 PyObject *cls = NULL;
41 Py_ssize_t nargs, nbases;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043 assert(args != NULL);
44 if (!PyTuple_Check(args)) {
45 PyErr_SetString(PyExc_TypeError,
46 "__build_class__: args is not a tuple");
47 return NULL;
48 }
49 nargs = PyTuple_GET_SIZE(args);
50 if (nargs < 2) {
51 PyErr_SetString(PyExc_TypeError,
52 "__build_class__: not enough arguments");
53 return NULL;
54 }
55 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
56 name = PyTuple_GET_ITEM(args, 1);
57 if (!PyUnicode_Check(name)) {
58 PyErr_SetString(PyExc_TypeError,
59 "__build_class__: name is not a string");
60 return NULL;
61 }
62 bases = PyTuple_GetSlice(args, 2, nargs);
63 if (bases == NULL)
64 return NULL;
65 nbases = nargs - 2;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 if (kwds == NULL) {
68 meta = NULL;
69 mkw = NULL;
70 }
71 else {
72 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
73 if (mkw == NULL) {
74 Py_DECREF(bases);
75 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000076 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 meta = PyDict_GetItemString(mkw, "metaclass");
78 if (meta != NULL) {
79 Py_INCREF(meta);
80 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
81 Py_DECREF(meta);
82 Py_DECREF(mkw);
83 Py_DECREF(bases);
84 return NULL;
85 }
86 }
87 }
88 if (meta == NULL) {
89 if (PyTuple_GET_SIZE(bases) == 0)
90 meta = (PyObject *) (&PyType_Type);
91 else {
92 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
93 meta = (PyObject *) (base0->ob_type);
94 }
95 Py_INCREF(meta);
96 }
97 prep = PyObject_GetAttrString(meta, "__prepare__");
98 if (prep == NULL) {
99 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
100 PyErr_Clear();
101 ns = PyDict_New();
102 }
103 else {
104 Py_DECREF(meta);
105 Py_XDECREF(mkw);
106 Py_DECREF(bases);
107 return NULL;
108 }
109 }
110 else {
111 PyObject *pargs = PyTuple_Pack(2, name, bases);
112 if (pargs == NULL) {
113 Py_DECREF(prep);
114 Py_DECREF(meta);
115 Py_XDECREF(mkw);
116 Py_DECREF(bases);
117 return NULL;
118 }
119 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
120 Py_DECREF(pargs);
121 Py_DECREF(prep);
122 }
123 if (ns == NULL) {
124 Py_DECREF(meta);
125 Py_XDECREF(mkw);
126 Py_DECREF(bases);
127 return NULL;
128 }
129 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
130 if (cell != NULL) {
131 PyObject *margs;
132 margs = PyTuple_Pack(3, name, bases, ns);
133 if (margs != NULL) {
134 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
135 Py_DECREF(margs);
136 }
137 if (cls != NULL && PyCell_Check(cell)) {
138 Py_INCREF(cls);
139 PyCell_SET(cell, cls);
140 }
141 Py_DECREF(cell);
142 }
143 Py_DECREF(ns);
144 Py_DECREF(meta);
145 Py_XDECREF(mkw);
146 Py_DECREF(bases);
147 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000148}
149
150PyDoc_STRVAR(build_class_doc,
151"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
152\n\
153Internal helper function used by the class statement.");
154
155static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000156builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
159 "level", 0};
160 char *name;
161 PyObject *globals = NULL;
162 PyObject *locals = NULL;
163 PyObject *fromlist = NULL;
164 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
167 kwlist, &name, &globals, &locals, &fromlist, &level))
168 return NULL;
169 return PyImport_ImportModuleLevel(name, globals, locals,
170 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000171}
172
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000173PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000174"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000175\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000176Import a module. Because this function is meant for use by the Python\n\
177interpreter and not for general use it is better to use\n\
178importlib.import_module() to programmatically import a module.\n\
179\n\
180The globals argument is only used to determine the context;\n\
181they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000182should be a list of names to emulate ``from name import ...'', or an\n\
183empty list to emulate ``import name''.\n\
184When importing a module from a package, note that __import__('A.B', ...)\n\
185returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000186fromlist is not empty. Level is used to determine whether to perform \n\
187absolute or relative imports. -1 is the original strategy of attempting\n\
188both absolute and relative imports, 0 is absolute, a positive number\n\
189is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000190
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000191
Guido van Rossum79f25d91997-04-29 20:08:16 +0000192static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000193builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000196}
197
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000198PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000199"abs(number) -> number\n\
200\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000201Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000202
Raymond Hettinger96229b12005-03-11 06:49:40 +0000203static PyObject *
204builtin_all(PyObject *self, PyObject *v)
205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 PyObject *it, *item;
207 PyObject *(*iternext)(PyObject *);
208 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 it = PyObject_GetIter(v);
211 if (it == NULL)
212 return NULL;
213 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 for (;;) {
216 item = iternext(it);
217 if (item == NULL)
218 break;
219 cmp = PyObject_IsTrue(item);
220 Py_DECREF(item);
221 if (cmp < 0) {
222 Py_DECREF(it);
223 return NULL;
224 }
225 if (cmp == 0) {
226 Py_DECREF(it);
227 Py_RETURN_FALSE;
228 }
229 }
230 Py_DECREF(it);
231 if (PyErr_Occurred()) {
232 if (PyErr_ExceptionMatches(PyExc_StopIteration))
233 PyErr_Clear();
234 else
235 return NULL;
236 }
237 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000238}
239
240PyDoc_STRVAR(all_doc,
241"all(iterable) -> bool\n\
242\n\
243Return True if bool(x) is True for all values x in the iterable.");
244
245static PyObject *
246builtin_any(PyObject *self, PyObject *v)
247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 PyObject *it, *item;
249 PyObject *(*iternext)(PyObject *);
250 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 it = PyObject_GetIter(v);
253 if (it == NULL)
254 return NULL;
255 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 for (;;) {
258 item = iternext(it);
259 if (item == NULL)
260 break;
261 cmp = PyObject_IsTrue(item);
262 Py_DECREF(item);
263 if (cmp < 0) {
264 Py_DECREF(it);
265 return NULL;
266 }
267 if (cmp == 1) {
268 Py_DECREF(it);
269 Py_RETURN_TRUE;
270 }
271 }
272 Py_DECREF(it);
273 if (PyErr_Occurred()) {
274 if (PyErr_ExceptionMatches(PyExc_StopIteration))
275 PyErr_Clear();
276 else
277 return NULL;
278 }
279 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000280}
281
282PyDoc_STRVAR(any_doc,
283"any(iterable) -> bool\n\
284\n\
285Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000286
Georg Brandl559e5d72008-06-11 18:37:52 +0000287static PyObject *
288builtin_ascii(PyObject *self, PyObject *v)
289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000291}
292
293PyDoc_STRVAR(ascii_doc,
294"ascii(object) -> string\n\
295\n\
296As repr(), return a string containing a printable representation of an\n\
297object, but escape the non-ASCII characters in the string returned by\n\
298repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
299to that returned by repr() in Python 2.");
300
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000301
Guido van Rossum79f25d91997-04-29 20:08:16 +0000302static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000303builtin_bin(PyObject *self, PyObject *v)
304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000306}
307
308PyDoc_STRVAR(bin_doc,
309"bin(number) -> string\n\
310\n\
311Return the binary representation of an integer or long integer.");
312
313
Raymond Hettinger17301e92008-03-13 00:19:26 +0000314typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 PyObject_HEAD
316 PyObject *func;
317 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000318} filterobject;
319
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000320static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000321filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 PyObject *func, *seq;
324 PyObject *it;
325 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
328 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
331 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 /* Get iterator. */
334 it = PyObject_GetIter(seq);
335 if (it == NULL)
336 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 /* create filterobject structure */
339 lz = (filterobject *)type->tp_alloc(type, 0);
340 if (lz == NULL) {
341 Py_DECREF(it);
342 return NULL;
343 }
344 Py_INCREF(func);
345 lz->func = func;
346 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000349}
350
351static void
352filter_dealloc(filterobject *lz)
353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 PyObject_GC_UnTrack(lz);
355 Py_XDECREF(lz->func);
356 Py_XDECREF(lz->it);
357 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000358}
359
360static int
361filter_traverse(filterobject *lz, visitproc visit, void *arg)
362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 Py_VISIT(lz->it);
364 Py_VISIT(lz->func);
365 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000366}
367
368static PyObject *
369filter_next(filterobject *lz)
370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 PyObject *item;
372 PyObject *it = lz->it;
373 long ok;
374 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 iternext = *Py_TYPE(it)->tp_iternext;
377 for (;;) {
378 item = iternext(it);
379 if (item == NULL)
380 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
383 ok = PyObject_IsTrue(item);
384 } else {
385 PyObject *good;
386 good = PyObject_CallFunctionObjArgs(lz->func,
387 item, NULL);
388 if (good == NULL) {
389 Py_DECREF(item);
390 return NULL;
391 }
392 ok = PyObject_IsTrue(good);
393 Py_DECREF(good);
394 }
395 if (ok)
396 return item;
397 Py_DECREF(item);
398 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000399}
400
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000401PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000402"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000403\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000404Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000405is true. If function is None, return the items that are true.");
406
407PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 PyVarObject_HEAD_INIT(&PyType_Type, 0)
409 "filter", /* tp_name */
410 sizeof(filterobject), /* tp_basicsize */
411 0, /* tp_itemsize */
412 /* methods */
413 (destructor)filter_dealloc, /* tp_dealloc */
414 0, /* tp_print */
415 0, /* tp_getattr */
416 0, /* tp_setattr */
417 0, /* tp_reserved */
418 0, /* tp_repr */
419 0, /* tp_as_number */
420 0, /* tp_as_sequence */
421 0, /* tp_as_mapping */
422 0, /* tp_hash */
423 0, /* tp_call */
424 0, /* tp_str */
425 PyObject_GenericGetAttr, /* tp_getattro */
426 0, /* tp_setattro */
427 0, /* tp_as_buffer */
428 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
429 Py_TPFLAGS_BASETYPE, /* tp_flags */
430 filter_doc, /* tp_doc */
431 (traverseproc)filter_traverse, /* tp_traverse */
432 0, /* tp_clear */
433 0, /* tp_richcompare */
434 0, /* tp_weaklistoffset */
435 PyObject_SelfIter, /* tp_iter */
436 (iternextfunc)filter_next, /* tp_iternext */
437 0, /* tp_methods */
438 0, /* tp_members */
439 0, /* tp_getset */
440 0, /* tp_base */
441 0, /* tp_dict */
442 0, /* tp_descr_get */
443 0, /* tp_descr_set */
444 0, /* tp_dictoffset */
445 0, /* tp_init */
446 PyType_GenericAlloc, /* tp_alloc */
447 filter_new, /* tp_new */
448 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000449};
450
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000451
Eric Smith8c663262007-08-25 02:26:07 +0000452static PyObject *
453builtin_format(PyObject *self, PyObject *args)
454{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000455 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000456 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000457
Eric Smith8fd3eba2008-02-17 19:48:00 +0000458 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000460
Eric Smith8fd3eba2008-02-17 19:48:00 +0000461 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000462}
463
Eric Smith8c663262007-08-25 02:26:07 +0000464PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000465"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000466\n\
Eric Smith81936692007-08-31 01:14:01 +0000467Returns value.__format__(format_spec)\n\
468format_spec defaults to \"\"");
469
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000470static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000471builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 if (!PyArg_ParseTuple(args, "i:chr", &x))
476 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000479}
480
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000481PyDoc_VAR(chr_doc) = PyDoc_STR(
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000482"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000483\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000484Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000485)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000486#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000487PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000488"\nIf 0x10000 <= i, a surrogate pair is returned."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000489)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000490#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000491;
Guido van Rossum09095f32000-03-10 23:00:52 +0000492
493
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000494static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000495source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 char *str;
498 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 if (PyUnicode_Check(cmd)) {
501 cf->cf_flags |= PyCF_IGNORE_COOKIE;
502 cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL);
503 if (cmd == NULL)
504 return NULL;
505 }
506 else if (!PyObject_CheckReadBuffer(cmd)) {
507 PyErr_Format(PyExc_TypeError,
508 "%s() arg 1 must be a %s object",
509 funcname, what);
510 return NULL;
511 }
512 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
513 return NULL;
514 }
515 if (strlen(str) != size) {
516 PyErr_SetString(PyExc_TypeError,
517 "source code string cannot contain null bytes");
518 return NULL;
519 }
520 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000521}
522
Guido van Rossum79f25d91997-04-29 20:08:16 +0000523static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000524builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 char *str;
527 char *filename;
528 char *startstr;
529 int mode = -1;
530 int dont_inherit = 0;
531 int supplied_flags = 0;
532 int is_ast;
533 PyCompilerFlags cf;
534 PyObject *cmd;
535 static char *kwlist[] = {"source", "filename", "mode", "flags",
536 "dont_inherit", NULL};
537 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
540 kwlist, &cmd, &filename, &startstr,
541 &supplied_flags, &dont_inherit))
542 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 if (supplied_flags &
547 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
548 {
549 PyErr_SetString(PyExc_ValueError,
550 "compile(): unrecognised flags");
551 return NULL;
552 }
553 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 if (!dont_inherit) {
556 PyEval_MergeCompilerFlags(&cf);
557 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 if (strcmp(startstr, "exec") == 0)
560 mode = 0;
561 else if (strcmp(startstr, "eval") == 0)
562 mode = 1;
563 else if (strcmp(startstr, "single") == 0)
564 mode = 2;
565 else {
566 PyErr_SetString(PyExc_ValueError,
567 "compile() arg 3 must be 'exec', 'eval' or 'single'");
568 return NULL;
569 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 is_ast = PyAST_Check(cmd);
572 if (is_ast == -1)
573 return NULL;
574 if (is_ast) {
575 PyObject *result;
576 if (supplied_flags & PyCF_ONLY_AST) {
577 Py_INCREF(cmd);
578 result = cmd;
579 }
580 else {
581 PyArena *arena;
582 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 arena = PyArena_New();
585 mod = PyAST_obj2mod(cmd, arena, mode);
586 if (mod == NULL) {
587 PyArena_Free(arena);
588 return NULL;
589 }
590 result = (PyObject*)PyAST_Compile(mod, filename,
591 &cf, arena);
592 PyArena_Free(arena);
593 }
594 return result;
595 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
598 if (str == NULL)
599 return NULL;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 return Py_CompileStringFlags(str, filename, start[mode], &cf);
Guido van Rossum5b722181993-03-30 17:46:03 +0000602}
603
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000604PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000605"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000606\n\
607Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000608into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000609The filename will be used for run-time error messages.\n\
610The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000611single (interactive) statement, or 'eval' to compile an expression.\n\
612The flags argument, if present, controls which future statements influence\n\
613the compilation of the code.\n\
614The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
615the effects of any future statements in effect in the code calling\n\
616compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000617in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000618
Guido van Rossum79f25d91997-04-29 20:08:16 +0000619static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000620builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
625 return NULL;
626 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000627}
628
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000629PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000630"dir([object]) -> list of strings\n"
631"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000632"If called without an argument, return the names in the current scope.\n"
633"Else, return an alphabetized list of names comprising (some of) the attributes\n"
634"of the given object, and of attributes reachable from it.\n"
635"If the object supplies a method named __dir__, it will be used; otherwise\n"
636"the default dir() logic is used and returns:\n"
637" for a module object: the module's attributes.\n"
638" for a class object: its attributes, and recursively the attributes\n"
639" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000640" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000641" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000642
Guido van Rossum79f25d91997-04-29 20:08:16 +0000643static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000644builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
649 return NULL;
650 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000651}
652
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000653PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000654"divmod(x, y) -> (div, mod)\n\
655\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000656Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000657
658
Guido van Rossum79f25d91997-04-29 20:08:16 +0000659static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000660builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 PyObject *cmd, *result, *tmp = NULL;
663 PyObject *globals = Py_None, *locals = Py_None;
664 char *str;
665 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
668 return NULL;
669 if (locals != Py_None && !PyMapping_Check(locals)) {
670 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
671 return NULL;
672 }
673 if (globals != Py_None && !PyDict_Check(globals)) {
674 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
675 "globals must be a real dict; try eval(expr, {}, mapping)"
676 : "globals must be a dict");
677 return NULL;
678 }
679 if (globals == Py_None) {
680 globals = PyEval_GetGlobals();
681 if (locals == Py_None)
682 locals = PyEval_GetLocals();
683 }
684 else if (locals == Py_None)
685 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 if (globals == NULL || locals == NULL) {
688 PyErr_SetString(PyExc_TypeError,
689 "eval must be given globals and locals "
690 "when called without a frame");
691 return NULL;
692 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
695 if (PyDict_SetItemString(globals, "__builtins__",
696 PyEval_GetBuiltins()) != 0)
697 return NULL;
698 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 if (PyCode_Check(cmd)) {
701 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
702 PyErr_SetString(PyExc_TypeError,
703 "code object passed to eval() may not contain free variables");
704 return NULL;
705 }
706 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
707 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
710 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
711 if (str == NULL)
712 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 while (*str == ' ' || *str == '\t')
715 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 (void)PyEval_MergeCompilerFlags(&cf);
718 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
719 Py_XDECREF(tmp);
720 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000721}
722
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000723PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000724"eval(source[, globals[, locals]]) -> value\n\
725\n\
726Evaluate the source in the context of globals and locals.\n\
727The source may be a string representing a Python expression\n\
728or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000729The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000730defaulting to the current globals and locals.\n\
731If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000732
Georg Brandl7cae87c2006-09-06 06:51:57 +0000733static PyObject *
734builtin_exec(PyObject *self, PyObject *args)
735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 PyObject *v;
737 PyObject *prog, *globals = Py_None, *locals = Py_None;
738 int plain = 0;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
741 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 if (globals == Py_None) {
744 globals = PyEval_GetGlobals();
745 if (locals == Py_None) {
746 locals = PyEval_GetLocals();
747 plain = 1;
748 }
749 if (!globals || !locals) {
750 PyErr_SetString(PyExc_SystemError,
751 "globals and locals cannot be NULL");
752 return NULL;
753 }
754 }
755 else if (locals == Py_None)
756 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 if (!PyDict_Check(globals)) {
759 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
760 globals->ob_type->tp_name);
761 return NULL;
762 }
763 if (!PyMapping_Check(locals)) {
764 PyErr_Format(PyExc_TypeError,
765 "arg 3 must be a mapping or None, not %.100s",
766 locals->ob_type->tp_name);
767 return NULL;
768 }
769 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
770 if (PyDict_SetItemString(globals, "__builtins__",
771 PyEval_GetBuiltins()) != 0)
772 return NULL;
773 }
774
775 if (PyCode_Check(prog)) {
776 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
777 PyErr_SetString(PyExc_TypeError,
778 "code object passed to exec() may not "
779 "contain free variables");
780 return NULL;
781 }
782 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
783 }
784 else {
785 char *str;
786 PyCompilerFlags cf;
787 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
788 str = source_as_string(prog, "exec",
789 "string, bytes or code", &cf);
790 if (str == NULL)
791 return NULL;
792 if (PyEval_MergeCompilerFlags(&cf))
793 v = PyRun_StringFlags(str, Py_file_input, globals,
794 locals, &cf);
795 else
796 v = PyRun_String(str, Py_file_input, globals, locals);
797 }
798 if (v == NULL)
799 return NULL;
800 Py_DECREF(v);
801 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000802}
803
804PyDoc_STRVAR(exec_doc,
805"exec(object[, globals[, locals]])\n\
806\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000807Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000808object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000809The globals and locals are dictionaries, defaulting to the current\n\
810globals and locals. If only globals is given, locals defaults to it.");
811
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000812
Guido van Rossum79f25d91997-04-29 20:08:16 +0000813static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000814builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 PyObject *v, *result, *dflt = NULL;
817 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
820 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 if (!PyUnicode_Check(name)) {
823 PyErr_SetString(PyExc_TypeError,
824 "getattr(): attribute name must be string");
825 return NULL;
826 }
827 result = PyObject_GetAttr(v, name);
828 if (result == NULL && dflt != NULL &&
829 PyErr_ExceptionMatches(PyExc_AttributeError))
830 {
831 PyErr_Clear();
832 Py_INCREF(dflt);
833 result = dflt;
834 }
835 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000836}
837
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000838PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000839"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000840\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000841Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
842When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000843exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000844
845
Guido van Rossum79f25d91997-04-29 20:08:16 +0000846static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000847builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 d = PyEval_GetGlobals();
852 Py_XINCREF(d);
853 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000854}
855
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000856PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000857"globals() -> dictionary\n\
858\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000859Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000860
861
Guido van Rossum79f25d91997-04-29 20:08:16 +0000862static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000863builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 PyObject *v;
866 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
869 return NULL;
870 if (!PyUnicode_Check(name)) {
871 PyErr_SetString(PyExc_TypeError,
872 "hasattr(): attribute name must be string");
873 return NULL;
874 }
875 v = PyObject_GetAttr(v, name);
876 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000877 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000879 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000881 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 }
883 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000884 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000885}
886
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000887PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000888"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000889\n\
890Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000891(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000892
893
Guido van Rossum79f25d91997-04-29 20:08:16 +0000894static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000895builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000898}
899
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000900PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000901"id(object) -> integer\n\
902\n\
903Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000904simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000905
906
Raymond Hettingera6c60372008-03-13 01:26:19 +0000907/* map object ************************************************************/
908
909typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 PyObject_HEAD
911 PyObject *iters;
912 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000913} mapobject;
914
Guido van Rossum79f25d91997-04-29 20:08:16 +0000915static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000916map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 PyObject *it, *iters, *func;
919 mapobject *lz;
920 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
923 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 numargs = PyTuple_Size(args);
926 if (numargs < 2) {
927 PyErr_SetString(PyExc_TypeError,
928 "map() must have at least two arguments.");
929 return NULL;
930 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 iters = PyTuple_New(numargs-1);
933 if (iters == NULL)
934 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 for (i=1 ; i<numargs ; i++) {
937 /* Get iterator. */
938 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
939 if (it == NULL) {
940 Py_DECREF(iters);
941 return NULL;
942 }
943 PyTuple_SET_ITEM(iters, i-1, it);
944 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 /* create mapobject structure */
947 lz = (mapobject *)type->tp_alloc(type, 0);
948 if (lz == NULL) {
949 Py_DECREF(iters);
950 return NULL;
951 }
952 lz->iters = iters;
953 func = PyTuple_GET_ITEM(args, 0);
954 Py_INCREF(func);
955 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000958}
959
960static void
961map_dealloc(mapobject *lz)
962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 PyObject_GC_UnTrack(lz);
964 Py_XDECREF(lz->iters);
965 Py_XDECREF(lz->func);
966 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +0000967}
968
969static int
970map_traverse(mapobject *lz, visitproc visit, void *arg)
971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 Py_VISIT(lz->iters);
973 Py_VISIT(lz->func);
974 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000975}
976
977static PyObject *
978map_next(mapobject *lz)
979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 PyObject *val;
981 PyObject *argtuple;
982 PyObject *result;
983 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 numargs = PyTuple_Size(lz->iters);
986 argtuple = PyTuple_New(numargs);
987 if (argtuple == NULL)
988 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 for (i=0 ; i<numargs ; i++) {
991 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
992 if (val == NULL) {
993 Py_DECREF(argtuple);
994 return NULL;
995 }
996 PyTuple_SET_ITEM(argtuple, i, val);
997 }
998 result = PyObject_Call(lz->func, argtuple, NULL);
999 Py_DECREF(argtuple);
1000 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001001}
1002
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001003PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001004"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001005\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001006Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001008
Raymond Hettingera6c60372008-03-13 01:26:19 +00001009PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1011 "map", /* tp_name */
1012 sizeof(mapobject), /* tp_basicsize */
1013 0, /* tp_itemsize */
1014 /* methods */
1015 (destructor)map_dealloc, /* tp_dealloc */
1016 0, /* tp_print */
1017 0, /* tp_getattr */
1018 0, /* tp_setattr */
1019 0, /* tp_reserved */
1020 0, /* tp_repr */
1021 0, /* tp_as_number */
1022 0, /* tp_as_sequence */
1023 0, /* tp_as_mapping */
1024 0, /* tp_hash */
1025 0, /* tp_call */
1026 0, /* tp_str */
1027 PyObject_GenericGetAttr, /* tp_getattro */
1028 0, /* tp_setattro */
1029 0, /* tp_as_buffer */
1030 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1031 Py_TPFLAGS_BASETYPE, /* tp_flags */
1032 map_doc, /* tp_doc */
1033 (traverseproc)map_traverse, /* tp_traverse */
1034 0, /* tp_clear */
1035 0, /* tp_richcompare */
1036 0, /* tp_weaklistoffset */
1037 PyObject_SelfIter, /* tp_iter */
1038 (iternextfunc)map_next, /* tp_iternext */
1039 0, /* tp_methods */
1040 0, /* tp_members */
1041 0, /* tp_getset */
1042 0, /* tp_base */
1043 0, /* tp_dict */
1044 0, /* tp_descr_get */
1045 0, /* tp_descr_set */
1046 0, /* tp_dictoffset */
1047 0, /* tp_init */
1048 PyType_GenericAlloc, /* tp_alloc */
1049 map_new, /* tp_new */
1050 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001051};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001052
Guido van Rossum79f25d91997-04-29 20:08:16 +00001053static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001054builtin_next(PyObject *self, PyObject *args)
1055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 PyObject *it, *res;
1057 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1060 return NULL;
1061 if (!PyIter_Check(it)) {
1062 PyErr_Format(PyExc_TypeError,
1063 "%.200s object is not an iterator",
1064 it->ob_type->tp_name);
1065 return NULL;
1066 }
1067
1068 res = (*it->ob_type->tp_iternext)(it);
1069 if (res != NULL) {
1070 return res;
1071 } else if (def != NULL) {
1072 if (PyErr_Occurred()) {
1073 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1074 return NULL;
1075 PyErr_Clear();
1076 }
1077 Py_INCREF(def);
1078 return def;
1079 } else if (PyErr_Occurred()) {
1080 return NULL;
1081 } else {
1082 PyErr_SetNone(PyExc_StopIteration);
1083 return NULL;
1084 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001085}
1086
1087PyDoc_STRVAR(next_doc,
1088"next(iterator[, default])\n\
1089\n\
1090Return the next item from the iterator. If default is given and the iterator\n\
1091is exhausted, it is returned instead of raising StopIteration.");
1092
1093
1094static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001095builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 PyObject *v;
1098 PyObject *name;
1099 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1102 return NULL;
1103 if (PyObject_SetAttr(v, name, value) != 0)
1104 return NULL;
1105 Py_INCREF(Py_None);
1106 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001107}
1108
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001109PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001110"setattr(object, name, value)\n\
1111\n\
1112Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001113``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001114
1115
Guido van Rossum79f25d91997-04-29 20:08:16 +00001116static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001117builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 PyObject *v;
1120 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1123 return NULL;
1124 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1125 return NULL;
1126 Py_INCREF(Py_None);
1127 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001128}
1129
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001130PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001131"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001132\n\
1133Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001134``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001135
1136
Guido van Rossum79f25d91997-04-29 20:08:16 +00001137static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001138builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 x = PyObject_Hash(v);
1143 if (x == -1)
1144 return NULL;
1145 return PyLong_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001146}
1147
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001148PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001149"hash(object) -> integer\n\
1150\n\
1151Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001152the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001153
1154
Guido van Rossum79f25d91997-04-29 20:08:16 +00001155static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001156builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001159}
1160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001161PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001162"hex(number) -> string\n\
1163\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001164Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001165
1166
Guido van Rossum79f25d91997-04-29 20:08:16 +00001167static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001168builtin_iter(PyObject *self, PyObject *args)
1169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1173 return NULL;
1174 if (w == NULL)
1175 return PyObject_GetIter(v);
1176 if (!PyCallable_Check(v)) {
1177 PyErr_SetString(PyExc_TypeError,
1178 "iter(v, w): v must be callable");
1179 return NULL;
1180 }
1181 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001182}
1183
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001184PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001185"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001186iter(callable, sentinel) -> iterator\n\
1187\n\
1188Get an iterator from an object. In the first form, the argument must\n\
1189supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001190In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001191
1192
1193static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001194builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 res = PyObject_Size(v);
1199 if (res < 0 && PyErr_Occurred())
1200 return NULL;
1201 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001202}
1203
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001204PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001205"len(object) -> integer\n\
1206\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001207Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001208
1209
Guido van Rossum79f25d91997-04-29 20:08:16 +00001210static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001211builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 d = PyEval_GetLocals();
1216 Py_XINCREF(d);
1217 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001218}
1219
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001220PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001221"locals() -> dictionary\n\
1222\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001223Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001224
1225
Guido van Rossum79f25d91997-04-29 20:08:16 +00001226static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001227min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1230 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 if (PyTuple_Size(args) > 1)
1233 v = args;
1234 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1235 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1238 keyfunc = PyDict_GetItemString(kwds, "key");
1239 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1240 PyErr_Format(PyExc_TypeError,
1241 "%s() got an unexpected keyword argument", name);
1242 return NULL;
1243 }
1244 Py_INCREF(keyfunc);
1245 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 it = PyObject_GetIter(v);
1248 if (it == NULL) {
1249 Py_XDECREF(keyfunc);
1250 return NULL;
1251 }
Tim Petersc3074532001-05-03 07:00:32 +00001252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 maxitem = NULL; /* the result */
1254 maxval = NULL; /* the value associated with the result */
1255 while (( item = PyIter_Next(it) )) {
1256 /* get the value from the key function */
1257 if (keyfunc != NULL) {
1258 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1259 if (val == NULL)
1260 goto Fail_it_item;
1261 }
1262 /* no key function; the value is the item */
1263 else {
1264 val = item;
1265 Py_INCREF(val);
1266 }
Tim Petersc3074532001-05-03 07:00:32 +00001267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 /* maximum value and item are unset; set them */
1269 if (maxval == NULL) {
1270 maxitem = item;
1271 maxval = val;
1272 }
1273 /* maximum value and item are set; update them as necessary */
1274 else {
1275 int cmp = PyObject_RichCompareBool(val, maxval, op);
1276 if (cmp < 0)
1277 goto Fail_it_item_and_val;
1278 else if (cmp > 0) {
1279 Py_DECREF(maxval);
1280 Py_DECREF(maxitem);
1281 maxval = val;
1282 maxitem = item;
1283 }
1284 else {
1285 Py_DECREF(item);
1286 Py_DECREF(val);
1287 }
1288 }
1289 }
1290 if (PyErr_Occurred())
1291 goto Fail_it;
1292 if (maxval == NULL) {
1293 PyErr_Format(PyExc_ValueError,
1294 "%s() arg is an empty sequence", name);
1295 assert(maxitem == NULL);
1296 }
1297 else
1298 Py_DECREF(maxval);
1299 Py_DECREF(it);
1300 Py_XDECREF(keyfunc);
1301 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001302
1303Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001305Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001307Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 Py_XDECREF(maxval);
1309 Py_XDECREF(maxitem);
1310 Py_DECREF(it);
1311 Py_XDECREF(keyfunc);
1312 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001313}
1314
Guido van Rossum79f25d91997-04-29 20:08:16 +00001315static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001316builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001319}
1320
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001321PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001322"min(iterable[, key=func]) -> value\n\
1323min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001324\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001325With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001326With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001327
1328
Guido van Rossum79f25d91997-04-29 20:08:16 +00001329static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001330builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001333}
1334
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001335PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001336"max(iterable[, key=func]) -> value\n\
1337max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001338\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001339With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001340With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001341
1342
Guido van Rossum79f25d91997-04-29 20:08:16 +00001343static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001344builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001347}
1348
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001349PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001350"oct(number) -> string\n\
1351\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001352Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001353
1354
Guido van Rossum79f25d91997-04-29 20:08:16 +00001355static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001356builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 long ord;
1359 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 if (PyBytes_Check(obj)) {
1362 size = PyBytes_GET_SIZE(obj);
1363 if (size == 1) {
1364 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1365 return PyLong_FromLong(ord);
1366 }
1367 }
1368 else if (PyUnicode_Check(obj)) {
1369 size = PyUnicode_GET_SIZE(obj);
1370 if (size == 1) {
1371 ord = (long)*PyUnicode_AS_UNICODE(obj);
1372 return PyLong_FromLong(ord);
1373 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001374#ifndef Py_UNICODE_WIDE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 if (size == 2) {
1376 /* Decode a valid surrogate pair */
1377 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1378 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1379 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1380 0xDC00 <= c1 && c1 <= 0xDFFF) {
1381 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1382 0x00010000);
1383 return PyLong_FromLong(ord);
1384 }
1385 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001386#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 }
1388 else if (PyByteArray_Check(obj)) {
1389 /* XXX Hopefully this is temporary */
1390 size = PyByteArray_GET_SIZE(obj);
1391 if (size == 1) {
1392 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1393 return PyLong_FromLong(ord);
1394 }
1395 }
1396 else {
1397 PyErr_Format(PyExc_TypeError,
1398 "ord() expected string of length 1, but " \
1399 "%.200s found", obj->ob_type->tp_name);
1400 return NULL;
1401 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 PyErr_Format(PyExc_TypeError,
1404 "ord() expected a character, "
1405 "but string of length %zd found",
1406 size);
1407 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001408}
1409
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001410PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001411"ord(c) -> integer\n\
1412\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001413Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001414)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001415#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001416PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001417"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001418)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001419#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001420;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001421
1422
Guido van Rossum79f25d91997-04-29 20:08:16 +00001423static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001424builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1429 return NULL;
1430 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001431}
1432
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001433PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001434"pow(x, y[, z]) -> number\n\
1435\n\
1436With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001437equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001438
1439
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001440
Guido van Rossum34343512006-11-30 22:13:52 +00001441static PyObject *
1442builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 static char *kwlist[] = {"sep", "end", "file", 0};
1445 static PyObject *dummy_args;
1446 PyObject *sep = NULL, *end = NULL, *file = NULL;
1447 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 if (dummy_args == NULL) {
1450 if (!(dummy_args = PyTuple_New(0)))
1451 return NULL;
1452 }
1453 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1454 kwlist, &sep, &end, &file))
1455 return NULL;
1456 if (file == NULL || file == Py_None) {
1457 file = PySys_GetObject("stdout");
1458 /* sys.stdout may be None when FILE* stdout isn't connected */
1459 if (file == Py_None)
1460 Py_RETURN_NONE;
1461 }
Guido van Rossum34343512006-11-30 22:13:52 +00001462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 if (sep == Py_None) {
1464 sep = NULL;
1465 }
1466 else if (sep && !PyUnicode_Check(sep)) {
1467 PyErr_Format(PyExc_TypeError,
1468 "sep must be None or a string, not %.200s",
1469 sep->ob_type->tp_name);
1470 return NULL;
1471 }
1472 if (end == Py_None) {
1473 end = NULL;
1474 }
1475 else if (end && !PyUnicode_Check(end)) {
1476 PyErr_Format(PyExc_TypeError,
1477 "end must be None or a string, not %.200s",
1478 end->ob_type->tp_name);
1479 return NULL;
1480 }
Guido van Rossum34343512006-11-30 22:13:52 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 for (i = 0; i < PyTuple_Size(args); i++) {
1483 if (i > 0) {
1484 if (sep == NULL)
1485 err = PyFile_WriteString(" ", file);
1486 else
1487 err = PyFile_WriteObject(sep, file,
1488 Py_PRINT_RAW);
1489 if (err)
1490 return NULL;
1491 }
1492 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1493 Py_PRINT_RAW);
1494 if (err)
1495 return NULL;
1496 }
Guido van Rossum34343512006-11-30 22:13:52 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 if (end == NULL)
1499 err = PyFile_WriteString("\n", file);
1500 else
1501 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1502 if (err)
1503 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001506}
1507
1508PyDoc_STRVAR(print_doc,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001509"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001510\n\
1511Prints the values to a stream, or to sys.stdout by default.\n\
1512Optional keyword arguments:\n\
1513file: a file-like object (stream); defaults to the current sys.stdout.\n\
1514sep: string inserted between values, default a space.\n\
1515end: string appended after the last value, default a newline.");
1516
1517
Guido van Rossuma88a0332007-02-26 16:59:55 +00001518static PyObject *
1519builtin_input(PyObject *self, PyObject *args)
1520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 PyObject *promptarg = NULL;
1522 PyObject *fin = PySys_GetObject("stdin");
1523 PyObject *fout = PySys_GetObject("stdout");
1524 PyObject *ferr = PySys_GetObject("stderr");
1525 PyObject *tmp;
1526 long fd;
1527 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 /* Parse arguments */
1530 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1531 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 /* Check that stdin/out/err are intact */
1534 if (fin == NULL || fin == Py_None) {
1535 PyErr_SetString(PyExc_RuntimeError,
1536 "input(): lost sys.stdin");
1537 return NULL;
1538 }
1539 if (fout == NULL || fout == Py_None) {
1540 PyErr_SetString(PyExc_RuntimeError,
1541 "input(): lost sys.stdout");
1542 return NULL;
1543 }
1544 if (ferr == NULL || ferr == Py_None) {
1545 PyErr_SetString(PyExc_RuntimeError,
1546 "input(): lost sys.stderr");
1547 return NULL;
1548 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 /* First of all, flush stderr */
1551 tmp = PyObject_CallMethod(ferr, "flush", "");
1552 if (tmp == NULL)
1553 PyErr_Clear();
1554 else
1555 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 /* We should only use (GNU) readline if Python's sys.stdin and
1558 sys.stdout are the same as C's stdin and stdout, because we
1559 need to pass it those. */
1560 tmp = PyObject_CallMethod(fin, "fileno", "");
1561 if (tmp == NULL) {
1562 PyErr_Clear();
1563 tty = 0;
1564 }
1565 else {
1566 fd = PyLong_AsLong(tmp);
1567 Py_DECREF(tmp);
1568 if (fd < 0 && PyErr_Occurred())
1569 return NULL;
1570 tty = fd == fileno(stdin) && isatty(fd);
1571 }
1572 if (tty) {
1573 tmp = PyObject_CallMethod(fout, "fileno", "");
1574 if (tmp == NULL)
1575 PyErr_Clear();
1576 else {
1577 fd = PyLong_AsLong(tmp);
1578 Py_DECREF(tmp);
1579 if (fd < 0 && PyErr_Occurred())
1580 return NULL;
1581 tty = fd == fileno(stdout) && isatty(fd);
1582 }
1583 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 /* If we're interactive, use (GNU) readline */
1586 if (tty) {
1587 PyObject *po;
1588 char *prompt;
1589 char *s;
1590 PyObject *stdin_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001591 char *stdin_encoding_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 PyObject *result;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1595 if (!stdin_encoding)
1596 /* stdin is a text stream, so it must have an
1597 encoding. */
1598 return NULL;
Victor Stinner306f0102010-05-19 01:06:22 +00001599 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
1600 if (stdin_encoding_str == NULL) {
1601 Py_DECREF(stdin_encoding);
1602 return NULL;
1603 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 tmp = PyObject_CallMethod(fout, "flush", "");
1605 if (tmp == NULL)
1606 PyErr_Clear();
1607 else
1608 Py_DECREF(tmp);
1609 if (promptarg != NULL) {
1610 PyObject *stringpo;
1611 PyObject *stdout_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001612 char *stdout_encoding_str;
1613 stdout_encoding = PyObject_GetAttrString(fout, "encoding");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 if (stdout_encoding == NULL) {
1615 Py_DECREF(stdin_encoding);
1616 return NULL;
1617 }
Victor Stinner306f0102010-05-19 01:06:22 +00001618 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
1619 if (stdout_encoding_str == NULL) {
1620 Py_DECREF(stdin_encoding);
1621 Py_DECREF(stdout_encoding);
1622 return NULL;
1623 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 stringpo = PyObject_Str(promptarg);
1625 if (stringpo == NULL) {
1626 Py_DECREF(stdin_encoding);
1627 Py_DECREF(stdout_encoding);
1628 return NULL;
1629 }
1630 po = PyUnicode_AsEncodedString(stringpo,
Victor Stinner306f0102010-05-19 01:06:22 +00001631 stdout_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 Py_DECREF(stdout_encoding);
1633 Py_DECREF(stringpo);
1634 if (po == NULL) {
1635 Py_DECREF(stdin_encoding);
1636 return NULL;
1637 }
1638 prompt = PyBytes_AsString(po);
1639 if (prompt == NULL) {
1640 Py_DECREF(stdin_encoding);
1641 Py_DECREF(po);
1642 return NULL;
1643 }
1644 }
1645 else {
1646 po = NULL;
1647 prompt = "";
1648 }
1649 s = PyOS_Readline(stdin, stdout, prompt);
1650 Py_XDECREF(po);
1651 if (s == NULL) {
1652 if (!PyErr_Occurred())
1653 PyErr_SetNone(PyExc_KeyboardInterrupt);
1654 Py_DECREF(stdin_encoding);
1655 return NULL;
1656 }
1657 if (*s == '\0') {
1658 PyErr_SetNone(PyExc_EOFError);
1659 result = NULL;
1660 }
1661 else { /* strip trailing '\n' */
1662 size_t len = strlen(s);
1663 if (len > PY_SSIZE_T_MAX) {
1664 PyErr_SetString(PyExc_OverflowError,
1665 "input: input too long");
1666 result = NULL;
1667 }
1668 else {
Victor Stinner306f0102010-05-19 01:06:22 +00001669 result = PyUnicode_Decode(s, len-1, stdin_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 }
1671 }
1672 Py_DECREF(stdin_encoding);
1673 PyMem_FREE(s);
1674 return result;
1675 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 /* Fallback if we're not interactive */
1678 if (promptarg != NULL) {
1679 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1680 return NULL;
1681 }
1682 tmp = PyObject_CallMethod(fout, "flush", "");
1683 if (tmp == NULL)
1684 PyErr_Clear();
1685 else
1686 Py_DECREF(tmp);
1687 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001688}
1689
1690PyDoc_STRVAR(input_doc,
1691"input([prompt]) -> string\n\
1692\n\
1693Read a string from standard input. The trailing newline is stripped.\n\
1694If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1695On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1696is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001697
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001698
Guido van Rossum79f25d91997-04-29 20:08:16 +00001699static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001700builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001703}
1704
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001705PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001706"repr(object) -> string\n\
1707\n\
1708Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001709For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001710
1711
Guido van Rossum79f25d91997-04-29 20:08:16 +00001712static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001713builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 static PyObject *round_str = NULL;
1716 PyObject *ndigits = NULL;
1717 static char *kwlist[] = {"number", "ndigits", 0};
1718 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1721 kwlist, &number, &ndigits))
1722 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 if (Py_TYPE(number)->tp_dict == NULL) {
1725 if (PyType_Ready(Py_TYPE(number)) < 0)
1726 return NULL;
1727 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 if (round_str == NULL) {
1730 round_str = PyUnicode_InternFromString("__round__");
1731 if (round_str == NULL)
1732 return NULL;
1733 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 round = _PyType_Lookup(Py_TYPE(number), round_str);
1736 if (round == NULL) {
1737 PyErr_Format(PyExc_TypeError,
1738 "type %.100s doesn't define __round__ method",
1739 Py_TYPE(number)->tp_name);
1740 return NULL;
1741 }
Alex Martelliae211f92007-08-22 23:21:33 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 if (ndigits == NULL)
1744 return PyObject_CallFunction(round, "O", number);
1745 else
1746 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001747}
1748
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001749PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001750"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001751\n\
1752Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001753This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001754same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001755
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001756
Raymond Hettinger64958a12003-12-17 20:43:33 +00001757static PyObject *
1758builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1761 PyObject *callable;
1762 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1763 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 /* args 1-3 should match listsort in Objects/listobject.c */
1766 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1767 kwlist, &seq, &keyfunc, &reverse))
1768 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 newlist = PySequence_List(seq);
1771 if (newlist == NULL)
1772 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 callable = PyObject_GetAttrString(newlist, "sort");
1775 if (callable == NULL) {
1776 Py_DECREF(newlist);
1777 return NULL;
1778 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 newargs = PyTuple_GetSlice(args, 1, 4);
1781 if (newargs == NULL) {
1782 Py_DECREF(newlist);
1783 Py_DECREF(callable);
1784 return NULL;
1785 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 v = PyObject_Call(callable, newargs, kwds);
1788 Py_DECREF(newargs);
1789 Py_DECREF(callable);
1790 if (v == NULL) {
1791 Py_DECREF(newlist);
1792 return NULL;
1793 }
1794 Py_DECREF(v);
1795 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001796}
1797
1798PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001799"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001800
Guido van Rossum79f25d91997-04-29 20:08:16 +00001801static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001802builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 PyObject *v = NULL;
1805 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1808 return NULL;
1809 if (v == NULL) {
1810 d = PyEval_GetLocals();
1811 if (d == NULL) {
1812 if (!PyErr_Occurred())
1813 PyErr_SetString(PyExc_SystemError,
1814 "vars(): no locals!?");
1815 }
1816 else
1817 Py_INCREF(d);
1818 }
1819 else {
1820 d = PyObject_GetAttrString(v, "__dict__");
1821 if (d == NULL) {
1822 PyErr_SetString(PyExc_TypeError,
1823 "vars() argument must have __dict__ attribute");
1824 return NULL;
1825 }
1826 }
1827 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001828}
1829
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001830PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001831"vars([object]) -> dictionary\n\
1832\n\
1833Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001834With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001835
Alex Martellia70b1912003-04-22 08:12:33 +00001836static PyObject*
1837builtin_sum(PyObject *self, PyObject *args)
1838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 PyObject *seq;
1840 PyObject *result = NULL;
1841 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1844 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 iter = PyObject_GetIter(seq);
1847 if (iter == NULL)
1848 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 if (result == NULL) {
1851 result = PyLong_FromLong(0);
1852 if (result == NULL) {
1853 Py_DECREF(iter);
1854 return NULL;
1855 }
1856 } else {
1857 /* reject string values for 'start' parameter */
1858 if (PyUnicode_Check(result)) {
1859 PyErr_SetString(PyExc_TypeError,
1860 "sum() can't sum strings [use ''.join(seq) instead]");
1861 Py_DECREF(iter);
1862 return NULL;
1863 }
1864 if (PyByteArray_Check(result)) {
1865 PyErr_SetString(PyExc_TypeError,
1866 "sum() can't sum bytes [use b''.join(seq) instead]");
1867 Py_DECREF(iter);
1868 return NULL;
1869 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 Py_INCREF(result);
1872 }
Alex Martellia70b1912003-04-22 08:12:33 +00001873
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001874#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1876 Assumes all inputs are the same type. If the assumption fails, default
1877 to the more general routine.
1878 */
1879 if (PyLong_CheckExact(result)) {
1880 int overflow;
1881 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1882 /* If this already overflowed, don't even enter the loop. */
1883 if (overflow == 0) {
1884 Py_DECREF(result);
1885 result = NULL;
1886 }
1887 while(result == NULL) {
1888 item = PyIter_Next(iter);
1889 if (item == NULL) {
1890 Py_DECREF(iter);
1891 if (PyErr_Occurred())
1892 return NULL;
1893 return PyLong_FromLong(i_result);
1894 }
1895 if (PyLong_CheckExact(item)) {
1896 long b = PyLong_AsLongAndOverflow(item, &overflow);
1897 long x = i_result + b;
1898 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1899 i_result = x;
1900 Py_DECREF(item);
1901 continue;
1902 }
1903 }
1904 /* Either overflowed or is not an int. Restore real objects and process normally */
1905 result = PyLong_FromLong(i_result);
1906 temp = PyNumber_Add(result, item);
1907 Py_DECREF(result);
1908 Py_DECREF(item);
1909 result = temp;
1910 if (result == NULL) {
1911 Py_DECREF(iter);
1912 return NULL;
1913 }
1914 }
1915 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 if (PyFloat_CheckExact(result)) {
1918 double f_result = PyFloat_AS_DOUBLE(result);
1919 Py_DECREF(result);
1920 result = NULL;
1921 while(result == NULL) {
1922 item = PyIter_Next(iter);
1923 if (item == NULL) {
1924 Py_DECREF(iter);
1925 if (PyErr_Occurred())
1926 return NULL;
1927 return PyFloat_FromDouble(f_result);
1928 }
1929 if (PyFloat_CheckExact(item)) {
1930 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1931 f_result += PyFloat_AS_DOUBLE(item);
1932 PyFPE_END_PROTECT(f_result)
1933 Py_DECREF(item);
1934 continue;
1935 }
1936 if (PyLong_CheckExact(item)) {
1937 long value;
1938 int overflow;
1939 value = PyLong_AsLongAndOverflow(item, &overflow);
1940 if (!overflow) {
1941 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1942 f_result += (double)value;
1943 PyFPE_END_PROTECT(f_result)
1944 Py_DECREF(item);
1945 continue;
1946 }
1947 }
1948 result = PyFloat_FromDouble(f_result);
1949 temp = PyNumber_Add(result, item);
1950 Py_DECREF(result);
1951 Py_DECREF(item);
1952 result = temp;
1953 if (result == NULL) {
1954 Py_DECREF(iter);
1955 return NULL;
1956 }
1957 }
1958 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001959#endif
1960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 for(;;) {
1962 item = PyIter_Next(iter);
1963 if (item == NULL) {
1964 /* error, or end-of-sequence */
1965 if (PyErr_Occurred()) {
1966 Py_DECREF(result);
1967 result = NULL;
1968 }
1969 break;
1970 }
1971 /* It's tempting to use PyNumber_InPlaceAdd instead of
1972 PyNumber_Add here, to avoid quadratic running time
1973 when doing 'sum(list_of_lists, [])'. However, this
1974 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00001975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 empty = []
1977 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00001978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 would change the value of empty. */
1980 temp = PyNumber_Add(result, item);
1981 Py_DECREF(result);
1982 Py_DECREF(item);
1983 result = temp;
1984 if (result == NULL)
1985 break;
1986 }
1987 Py_DECREF(iter);
1988 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00001989}
1990
1991PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001992"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00001993\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00001994Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
1995of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00001996empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00001997
1998
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001999static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002000builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 PyObject *inst;
2003 PyObject *cls;
2004 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2007 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 retval = PyObject_IsInstance(inst, cls);
2010 if (retval < 0)
2011 return NULL;
2012 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002013}
2014
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002015PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002016"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002017\n\
2018Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002019With a type as second argument, return whether that is the object's type.\n\
2020The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002021isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002022
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002023
2024static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002025builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 PyObject *derived;
2028 PyObject *cls;
2029 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2032 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 retval = PyObject_IsSubclass(derived, cls);
2035 if (retval < 0)
2036 return NULL;
2037 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002038}
2039
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002040PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002041"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002042\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002043Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2044When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2045is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002046
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002047
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002048typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 PyObject_HEAD
2050 Py_ssize_t tuplesize;
2051 PyObject *ittuple; /* tuple of iterators */
2052 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002053} zipobject;
2054
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002055static PyObject *
2056zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 zipobject *lz;
2059 Py_ssize_t i;
2060 PyObject *ittuple; /* tuple of iterators */
2061 PyObject *result;
2062 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2065 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 /* args must be a tuple */
2068 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 /* obtain iterators */
2071 ittuple = PyTuple_New(tuplesize);
2072 if (ittuple == NULL)
2073 return NULL;
2074 for (i=0; i < tuplesize; ++i) {
2075 PyObject *item = PyTuple_GET_ITEM(args, i);
2076 PyObject *it = PyObject_GetIter(item);
2077 if (it == NULL) {
2078 if (PyErr_ExceptionMatches(PyExc_TypeError))
2079 PyErr_Format(PyExc_TypeError,
2080 "zip argument #%zd must support iteration",
2081 i+1);
2082 Py_DECREF(ittuple);
2083 return NULL;
2084 }
2085 PyTuple_SET_ITEM(ittuple, i, it);
2086 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 /* create a result holder */
2089 result = PyTuple_New(tuplesize);
2090 if (result == NULL) {
2091 Py_DECREF(ittuple);
2092 return NULL;
2093 }
2094 for (i=0 ; i < tuplesize ; i++) {
2095 Py_INCREF(Py_None);
2096 PyTuple_SET_ITEM(result, i, Py_None);
2097 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 /* create zipobject structure */
2100 lz = (zipobject *)type->tp_alloc(type, 0);
2101 if (lz == NULL) {
2102 Py_DECREF(ittuple);
2103 Py_DECREF(result);
2104 return NULL;
2105 }
2106 lz->ittuple = ittuple;
2107 lz->tuplesize = tuplesize;
2108 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002111}
2112
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002113static void
2114zip_dealloc(zipobject *lz)
2115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 PyObject_GC_UnTrack(lz);
2117 Py_XDECREF(lz->ittuple);
2118 Py_XDECREF(lz->result);
2119 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002120}
2121
2122static int
2123zip_traverse(zipobject *lz, visitproc visit, void *arg)
2124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 Py_VISIT(lz->ittuple);
2126 Py_VISIT(lz->result);
2127 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002128}
2129
2130static PyObject *
2131zip_next(zipobject *lz)
2132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 Py_ssize_t i;
2134 Py_ssize_t tuplesize = lz->tuplesize;
2135 PyObject *result = lz->result;
2136 PyObject *it;
2137 PyObject *item;
2138 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 if (tuplesize == 0)
2141 return NULL;
2142 if (Py_REFCNT(result) == 1) {
2143 Py_INCREF(result);
2144 for (i=0 ; i < tuplesize ; i++) {
2145 it = PyTuple_GET_ITEM(lz->ittuple, i);
2146 item = (*Py_TYPE(it)->tp_iternext)(it);
2147 if (item == NULL) {
2148 Py_DECREF(result);
2149 return NULL;
2150 }
2151 olditem = PyTuple_GET_ITEM(result, i);
2152 PyTuple_SET_ITEM(result, i, item);
2153 Py_DECREF(olditem);
2154 }
2155 } else {
2156 result = PyTuple_New(tuplesize);
2157 if (result == NULL)
2158 return NULL;
2159 for (i=0 ; i < tuplesize ; i++) {
2160 it = PyTuple_GET_ITEM(lz->ittuple, i);
2161 item = (*Py_TYPE(it)->tp_iternext)(it);
2162 if (item == NULL) {
2163 Py_DECREF(result);
2164 return NULL;
2165 }
2166 PyTuple_SET_ITEM(result, i, item);
2167 }
2168 }
2169 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002170}
Barry Warsawbd599b52000-08-03 15:45:29 +00002171
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002172PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002173"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002174\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002175Return a zip object whose .__next__() method returns a tuple where\n\
2176the i-th element comes from the i-th iterable argument. The .__next__()\n\
2177method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002178is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002179
2180PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2182 "zip", /* tp_name */
2183 sizeof(zipobject), /* tp_basicsize */
2184 0, /* tp_itemsize */
2185 /* methods */
2186 (destructor)zip_dealloc, /* tp_dealloc */
2187 0, /* tp_print */
2188 0, /* tp_getattr */
2189 0, /* tp_setattr */
2190 0, /* tp_reserved */
2191 0, /* tp_repr */
2192 0, /* tp_as_number */
2193 0, /* tp_as_sequence */
2194 0, /* tp_as_mapping */
2195 0, /* tp_hash */
2196 0, /* tp_call */
2197 0, /* tp_str */
2198 PyObject_GenericGetAttr, /* tp_getattro */
2199 0, /* tp_setattro */
2200 0, /* tp_as_buffer */
2201 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2202 Py_TPFLAGS_BASETYPE, /* tp_flags */
2203 zip_doc, /* tp_doc */
2204 (traverseproc)zip_traverse, /* tp_traverse */
2205 0, /* tp_clear */
2206 0, /* tp_richcompare */
2207 0, /* tp_weaklistoffset */
2208 PyObject_SelfIter, /* tp_iter */
2209 (iternextfunc)zip_next, /* tp_iternext */
2210 0, /* tp_methods */
2211 0, /* tp_members */
2212 0, /* tp_getset */
2213 0, /* tp_base */
2214 0, /* tp_dict */
2215 0, /* tp_descr_get */
2216 0, /* tp_descr_set */
2217 0, /* tp_dictoffset */
2218 0, /* tp_init */
2219 PyType_GenericAlloc, /* tp_alloc */
2220 zip_new, /* tp_new */
2221 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002222};
Barry Warsawbd599b52000-08-03 15:45:29 +00002223
2224
Guido van Rossum79f25d91997-04-29 20:08:16 +00002225static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 {"__build_class__", (PyCFunction)builtin___build_class__,
2227 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2228 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2229 {"abs", builtin_abs, METH_O, abs_doc},
2230 {"all", builtin_all, METH_O, all_doc},
2231 {"any", builtin_any, METH_O, any_doc},
2232 {"ascii", builtin_ascii, METH_O, ascii_doc},
2233 {"bin", builtin_bin, METH_O, bin_doc},
2234 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2235 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2236 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2237 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2238 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2239 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2240 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2241 {"format", builtin_format, METH_VARARGS, format_doc},
2242 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2243 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2244 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2245 {"hash", builtin_hash, METH_O, hash_doc},
2246 {"hex", builtin_hex, METH_O, hex_doc},
2247 {"id", builtin_id, METH_O, id_doc},
2248 {"input", builtin_input, METH_VARARGS, input_doc},
2249 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2250 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2251 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2252 {"len", builtin_len, METH_O, len_doc},
2253 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2254 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2255 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2256 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2257 {"oct", builtin_oct, METH_O, oct_doc},
2258 {"ord", builtin_ord, METH_O, ord_doc},
2259 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2260 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2261 {"repr", builtin_repr, METH_O, repr_doc},
2262 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2263 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2264 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2265 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2266 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2267 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002268};
2269
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002270PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002271"Built-in functions, exceptions, and other objects.\n\
2272\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002273Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002274
Martin v. Löwis1a214512008-06-11 05:26:20 +00002275static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 PyModuleDef_HEAD_INIT,
2277 "builtins",
2278 builtin_doc,
2279 -1, /* multiple "initialization" just copies the module dict. */
2280 builtin_methods,
2281 NULL,
2282 NULL,
2283 NULL,
2284 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002285};
2286
2287
Guido van Rossum25ce5661997-08-02 03:10:38 +00002288PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002289_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 PyObject *mod, *dict, *debug;
2292 mod = PyModule_Create(&builtinsmodule);
2293 if (mod == NULL)
2294 return NULL;
2295 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002296
Tim Peters7571a0f2003-03-23 17:52:28 +00002297#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 /* "builtins" exposes a number of statically allocated objects
2299 * that, before this code was added in 2.3, never showed up in
2300 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2301 * result, programs leaking references to None and False (etc)
2302 * couldn't be diagnosed by examining sys.getobjects(0).
2303 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002304#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2305#else
2306#define ADD_TO_ALL(OBJECT) (void)0
2307#endif
2308
Tim Peters4b7625e2001-09-13 21:37:17 +00002309#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2311 return NULL; \
2312 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 SETBUILTIN("None", Py_None);
2315 SETBUILTIN("Ellipsis", Py_Ellipsis);
2316 SETBUILTIN("NotImplemented", Py_NotImplemented);
2317 SETBUILTIN("False", Py_False);
2318 SETBUILTIN("True", Py_True);
2319 SETBUILTIN("bool", &PyBool_Type);
2320 SETBUILTIN("memoryview", &PyMemoryView_Type);
2321 SETBUILTIN("bytearray", &PyByteArray_Type);
2322 SETBUILTIN("bytes", &PyBytes_Type);
2323 SETBUILTIN("classmethod", &PyClassMethod_Type);
2324 SETBUILTIN("complex", &PyComplex_Type);
2325 SETBUILTIN("dict", &PyDict_Type);
2326 SETBUILTIN("enumerate", &PyEnum_Type);
2327 SETBUILTIN("filter", &PyFilter_Type);
2328 SETBUILTIN("float", &PyFloat_Type);
2329 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2330 SETBUILTIN("property", &PyProperty_Type);
2331 SETBUILTIN("int", &PyLong_Type);
2332 SETBUILTIN("list", &PyList_Type);
2333 SETBUILTIN("map", &PyMap_Type);
2334 SETBUILTIN("object", &PyBaseObject_Type);
2335 SETBUILTIN("range", &PyRange_Type);
2336 SETBUILTIN("reversed", &PyReversed_Type);
2337 SETBUILTIN("set", &PySet_Type);
2338 SETBUILTIN("slice", &PySlice_Type);
2339 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2340 SETBUILTIN("str", &PyUnicode_Type);
2341 SETBUILTIN("super", &PySuper_Type);
2342 SETBUILTIN("tuple", &PyTuple_Type);
2343 SETBUILTIN("type", &PyType_Type);
2344 SETBUILTIN("zip", &PyZip_Type);
2345 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2346 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2347 Py_XDECREF(debug);
2348 return NULL;
2349 }
2350 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002353#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002354#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002355}