blob: 46045192cfdb58f820f7a71917de9f46c46b93a3 [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;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000527 PyObject *filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 char *filename;
529 char *startstr;
530 int mode = -1;
531 int dont_inherit = 0;
532 int supplied_flags = 0;
533 int is_ast;
534 PyCompilerFlags cf;
535 PyObject *cmd;
536 static char *kwlist[] = {"source", "filename", "mode", "flags",
537 "dont_inherit", NULL};
538 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000539 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000540
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000541 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|ii:compile", kwlist,
542 &cmd,
543 PyUnicode_FSConverter, &filename_obj,
544 &startstr, &supplied_flags,
545 &dont_inherit))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000547
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000548 filename = PyBytes_AS_STRING(filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 if (supplied_flags &
552 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
553 {
554 PyErr_SetString(PyExc_ValueError,
555 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000556 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 }
558 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 if (!dont_inherit) {
561 PyEval_MergeCompilerFlags(&cf);
562 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 if (strcmp(startstr, "exec") == 0)
565 mode = 0;
566 else if (strcmp(startstr, "eval") == 0)
567 mode = 1;
568 else if (strcmp(startstr, "single") == 0)
569 mode = 2;
570 else {
571 PyErr_SetString(PyExc_ValueError,
572 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000573 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 is_ast = PyAST_Check(cmd);
577 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000578 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 if (supplied_flags & PyCF_ONLY_AST) {
581 Py_INCREF(cmd);
582 result = cmd;
583 }
584 else {
585 PyArena *arena;
586 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 arena = PyArena_New();
589 mod = PyAST_obj2mod(cmd, arena, mode);
590 if (mod == NULL) {
591 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000592 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 }
594 result = (PyObject*)PyAST_Compile(mod, filename,
595 &cf, arena);
596 PyArena_Free(arena);
597 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000598 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
602 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000603 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000604
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000605 result = Py_CompileStringFlags(str, filename, start[mode], &cf);
606 goto finally;
607
608error:
609 result = NULL;
610finally:
611 Py_DECREF(filename_obj);
612 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000613}
614
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000615PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000616"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000617\n\
618Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000619into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000620The filename will be used for run-time error messages.\n\
621The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000622single (interactive) statement, or 'eval' to compile an expression.\n\
623The flags argument, if present, controls which future statements influence\n\
624the compilation of the code.\n\
625The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
626the effects of any future statements in effect in the code calling\n\
627compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000628in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000629
Guido van Rossum79f25d91997-04-29 20:08:16 +0000630static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000631builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
636 return NULL;
637 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000638}
639
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000640PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000641"dir([object]) -> list of strings\n"
642"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000643"If called without an argument, return the names in the current scope.\n"
644"Else, return an alphabetized list of names comprising (some of) the attributes\n"
645"of the given object, and of attributes reachable from it.\n"
646"If the object supplies a method named __dir__, it will be used; otherwise\n"
647"the default dir() logic is used and returns:\n"
648" for a module object: the module's attributes.\n"
649" for a class object: its attributes, and recursively the attributes\n"
650" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000651" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000652" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000653
Guido van Rossum79f25d91997-04-29 20:08:16 +0000654static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000655builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
660 return NULL;
661 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000662}
663
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000664PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000665"divmod(x, y) -> (div, mod)\n\
666\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000667Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000668
669
Guido van Rossum79f25d91997-04-29 20:08:16 +0000670static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000671builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 PyObject *cmd, *result, *tmp = NULL;
674 PyObject *globals = Py_None, *locals = Py_None;
675 char *str;
676 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
679 return NULL;
680 if (locals != Py_None && !PyMapping_Check(locals)) {
681 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
682 return NULL;
683 }
684 if (globals != Py_None && !PyDict_Check(globals)) {
685 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
686 "globals must be a real dict; try eval(expr, {}, mapping)"
687 : "globals must be a dict");
688 return NULL;
689 }
690 if (globals == Py_None) {
691 globals = PyEval_GetGlobals();
692 if (locals == Py_None)
693 locals = PyEval_GetLocals();
694 }
695 else if (locals == Py_None)
696 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 if (globals == NULL || locals == NULL) {
699 PyErr_SetString(PyExc_TypeError,
700 "eval must be given globals and locals "
701 "when called without a frame");
702 return NULL;
703 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
706 if (PyDict_SetItemString(globals, "__builtins__",
707 PyEval_GetBuiltins()) != 0)
708 return NULL;
709 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 if (PyCode_Check(cmd)) {
712 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
713 PyErr_SetString(PyExc_TypeError,
714 "code object passed to eval() may not contain free variables");
715 return NULL;
716 }
717 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
718 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
721 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
722 if (str == NULL)
723 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 while (*str == ' ' || *str == '\t')
726 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 (void)PyEval_MergeCompilerFlags(&cf);
729 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
730 Py_XDECREF(tmp);
731 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000732}
733
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000734PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000735"eval(source[, globals[, locals]]) -> value\n\
736\n\
737Evaluate the source in the context of globals and locals.\n\
738The source may be a string representing a Python expression\n\
739or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000740The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000741defaulting to the current globals and locals.\n\
742If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000743
Georg Brandl7cae87c2006-09-06 06:51:57 +0000744static PyObject *
745builtin_exec(PyObject *self, PyObject *args)
746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 PyObject *v;
748 PyObject *prog, *globals = Py_None, *locals = Py_None;
749 int plain = 0;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
752 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 if (globals == Py_None) {
755 globals = PyEval_GetGlobals();
756 if (locals == Py_None) {
757 locals = PyEval_GetLocals();
758 plain = 1;
759 }
760 if (!globals || !locals) {
761 PyErr_SetString(PyExc_SystemError,
762 "globals and locals cannot be NULL");
763 return NULL;
764 }
765 }
766 else if (locals == Py_None)
767 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (!PyDict_Check(globals)) {
770 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
771 globals->ob_type->tp_name);
772 return NULL;
773 }
774 if (!PyMapping_Check(locals)) {
775 PyErr_Format(PyExc_TypeError,
776 "arg 3 must be a mapping or None, not %.100s",
777 locals->ob_type->tp_name);
778 return NULL;
779 }
780 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
781 if (PyDict_SetItemString(globals, "__builtins__",
782 PyEval_GetBuiltins()) != 0)
783 return NULL;
784 }
785
786 if (PyCode_Check(prog)) {
787 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
788 PyErr_SetString(PyExc_TypeError,
789 "code object passed to exec() may not "
790 "contain free variables");
791 return NULL;
792 }
793 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
794 }
795 else {
796 char *str;
797 PyCompilerFlags cf;
798 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
799 str = source_as_string(prog, "exec",
800 "string, bytes or code", &cf);
801 if (str == NULL)
802 return NULL;
803 if (PyEval_MergeCompilerFlags(&cf))
804 v = PyRun_StringFlags(str, Py_file_input, globals,
805 locals, &cf);
806 else
807 v = PyRun_String(str, Py_file_input, globals, locals);
808 }
809 if (v == NULL)
810 return NULL;
811 Py_DECREF(v);
812 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000813}
814
815PyDoc_STRVAR(exec_doc,
816"exec(object[, globals[, locals]])\n\
817\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000818Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000819object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000820The globals and locals are dictionaries, defaulting to the current\n\
821globals and locals. If only globals is given, locals defaults to it.");
822
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000823
Guido van Rossum79f25d91997-04-29 20:08:16 +0000824static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000825builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 PyObject *v, *result, *dflt = NULL;
828 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
831 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 if (!PyUnicode_Check(name)) {
834 PyErr_SetString(PyExc_TypeError,
835 "getattr(): attribute name must be string");
836 return NULL;
837 }
838 result = PyObject_GetAttr(v, name);
839 if (result == NULL && dflt != NULL &&
840 PyErr_ExceptionMatches(PyExc_AttributeError))
841 {
842 PyErr_Clear();
843 Py_INCREF(dflt);
844 result = dflt;
845 }
846 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000847}
848
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000849PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000850"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000851\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000852Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
853When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000854exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000855
856
Guido van Rossum79f25d91997-04-29 20:08:16 +0000857static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000858builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 d = PyEval_GetGlobals();
863 Py_XINCREF(d);
864 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000865}
866
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000867PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000868"globals() -> dictionary\n\
869\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000870Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000871
872
Guido van Rossum79f25d91997-04-29 20:08:16 +0000873static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000874builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 PyObject *v;
877 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
880 return NULL;
881 if (!PyUnicode_Check(name)) {
882 PyErr_SetString(PyExc_TypeError,
883 "hasattr(): attribute name must be string");
884 return NULL;
885 }
886 v = PyObject_GetAttr(v, name);
887 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000888 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000890 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000892 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 }
894 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000895 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000896}
897
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000898PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000899"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000900\n\
901Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000902(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000903
904
Guido van Rossum79f25d91997-04-29 20:08:16 +0000905static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000906builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000909}
910
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000911PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000912"id(object) -> integer\n\
913\n\
914Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000915simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000916
917
Raymond Hettingera6c60372008-03-13 01:26:19 +0000918/* map object ************************************************************/
919
920typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 PyObject_HEAD
922 PyObject *iters;
923 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000924} mapobject;
925
Guido van Rossum79f25d91997-04-29 20:08:16 +0000926static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000927map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 PyObject *it, *iters, *func;
930 mapobject *lz;
931 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
934 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 numargs = PyTuple_Size(args);
937 if (numargs < 2) {
938 PyErr_SetString(PyExc_TypeError,
939 "map() must have at least two arguments.");
940 return NULL;
941 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 iters = PyTuple_New(numargs-1);
944 if (iters == NULL)
945 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 for (i=1 ; i<numargs ; i++) {
948 /* Get iterator. */
949 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
950 if (it == NULL) {
951 Py_DECREF(iters);
952 return NULL;
953 }
954 PyTuple_SET_ITEM(iters, i-1, it);
955 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 /* create mapobject structure */
958 lz = (mapobject *)type->tp_alloc(type, 0);
959 if (lz == NULL) {
960 Py_DECREF(iters);
961 return NULL;
962 }
963 lz->iters = iters;
964 func = PyTuple_GET_ITEM(args, 0);
965 Py_INCREF(func);
966 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000969}
970
971static void
972map_dealloc(mapobject *lz)
973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 PyObject_GC_UnTrack(lz);
975 Py_XDECREF(lz->iters);
976 Py_XDECREF(lz->func);
977 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +0000978}
979
980static int
981map_traverse(mapobject *lz, visitproc visit, void *arg)
982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 Py_VISIT(lz->iters);
984 Py_VISIT(lz->func);
985 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000986}
987
988static PyObject *
989map_next(mapobject *lz)
990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 PyObject *val;
992 PyObject *argtuple;
993 PyObject *result;
994 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 numargs = PyTuple_Size(lz->iters);
997 argtuple = PyTuple_New(numargs);
998 if (argtuple == NULL)
999 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 for (i=0 ; i<numargs ; i++) {
1002 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1003 if (val == NULL) {
1004 Py_DECREF(argtuple);
1005 return NULL;
1006 }
1007 PyTuple_SET_ITEM(argtuple, i, val);
1008 }
1009 result = PyObject_Call(lz->func, argtuple, NULL);
1010 Py_DECREF(argtuple);
1011 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001012}
1013
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001014PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001015"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001016\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001017Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001019
Raymond Hettingera6c60372008-03-13 01:26:19 +00001020PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1022 "map", /* tp_name */
1023 sizeof(mapobject), /* tp_basicsize */
1024 0, /* tp_itemsize */
1025 /* methods */
1026 (destructor)map_dealloc, /* tp_dealloc */
1027 0, /* tp_print */
1028 0, /* tp_getattr */
1029 0, /* tp_setattr */
1030 0, /* tp_reserved */
1031 0, /* tp_repr */
1032 0, /* tp_as_number */
1033 0, /* tp_as_sequence */
1034 0, /* tp_as_mapping */
1035 0, /* tp_hash */
1036 0, /* tp_call */
1037 0, /* tp_str */
1038 PyObject_GenericGetAttr, /* tp_getattro */
1039 0, /* tp_setattro */
1040 0, /* tp_as_buffer */
1041 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1042 Py_TPFLAGS_BASETYPE, /* tp_flags */
1043 map_doc, /* tp_doc */
1044 (traverseproc)map_traverse, /* tp_traverse */
1045 0, /* tp_clear */
1046 0, /* tp_richcompare */
1047 0, /* tp_weaklistoffset */
1048 PyObject_SelfIter, /* tp_iter */
1049 (iternextfunc)map_next, /* tp_iternext */
1050 0, /* tp_methods */
1051 0, /* tp_members */
1052 0, /* tp_getset */
1053 0, /* tp_base */
1054 0, /* tp_dict */
1055 0, /* tp_descr_get */
1056 0, /* tp_descr_set */
1057 0, /* tp_dictoffset */
1058 0, /* tp_init */
1059 PyType_GenericAlloc, /* tp_alloc */
1060 map_new, /* tp_new */
1061 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001062};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001063
Guido van Rossum79f25d91997-04-29 20:08:16 +00001064static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001065builtin_next(PyObject *self, PyObject *args)
1066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 PyObject *it, *res;
1068 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1071 return NULL;
1072 if (!PyIter_Check(it)) {
1073 PyErr_Format(PyExc_TypeError,
1074 "%.200s object is not an iterator",
1075 it->ob_type->tp_name);
1076 return NULL;
1077 }
1078
1079 res = (*it->ob_type->tp_iternext)(it);
1080 if (res != NULL) {
1081 return res;
1082 } else if (def != NULL) {
1083 if (PyErr_Occurred()) {
1084 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1085 return NULL;
1086 PyErr_Clear();
1087 }
1088 Py_INCREF(def);
1089 return def;
1090 } else if (PyErr_Occurred()) {
1091 return NULL;
1092 } else {
1093 PyErr_SetNone(PyExc_StopIteration);
1094 return NULL;
1095 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001096}
1097
1098PyDoc_STRVAR(next_doc,
1099"next(iterator[, default])\n\
1100\n\
1101Return the next item from the iterator. If default is given and the iterator\n\
1102is exhausted, it is returned instead of raising StopIteration.");
1103
1104
1105static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001106builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 PyObject *v;
1109 PyObject *name;
1110 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1113 return NULL;
1114 if (PyObject_SetAttr(v, name, value) != 0)
1115 return NULL;
1116 Py_INCREF(Py_None);
1117 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001118}
1119
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001120PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001121"setattr(object, name, value)\n\
1122\n\
1123Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001124``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001125
1126
Guido van Rossum79f25d91997-04-29 20:08:16 +00001127static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001128builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 PyObject *v;
1131 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1134 return NULL;
1135 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1136 return NULL;
1137 Py_INCREF(Py_None);
1138 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001139}
1140
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001141PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001142"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001143\n\
1144Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001145``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001146
1147
Guido van Rossum79f25d91997-04-29 20:08:16 +00001148static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001149builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001150{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001151 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 x = PyObject_Hash(v);
1154 if (x == -1)
1155 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001156 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001157}
1158
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001159PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001160"hash(object) -> integer\n\
1161\n\
1162Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001163the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001164
1165
Guido van Rossum79f25d91997-04-29 20:08:16 +00001166static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001167builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001170}
1171
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001172PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001173"hex(number) -> string\n\
1174\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001175Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001176
1177
Guido van Rossum79f25d91997-04-29 20:08:16 +00001178static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001179builtin_iter(PyObject *self, PyObject *args)
1180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1184 return NULL;
1185 if (w == NULL)
1186 return PyObject_GetIter(v);
1187 if (!PyCallable_Check(v)) {
1188 PyErr_SetString(PyExc_TypeError,
1189 "iter(v, w): v must be callable");
1190 return NULL;
1191 }
1192 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001193}
1194
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001195PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001196"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001197iter(callable, sentinel) -> iterator\n\
1198\n\
1199Get an iterator from an object. In the first form, the argument must\n\
1200supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001201In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001202
1203
1204static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001205builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 res = PyObject_Size(v);
1210 if (res < 0 && PyErr_Occurred())
1211 return NULL;
1212 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001213}
1214
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001215PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001216"len(object) -> integer\n\
1217\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001218Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001219
1220
Guido van Rossum79f25d91997-04-29 20:08:16 +00001221static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001222builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 d = PyEval_GetLocals();
1227 Py_XINCREF(d);
1228 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001229}
1230
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001231PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001232"locals() -> dictionary\n\
1233\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001234Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001235
1236
Guido van Rossum79f25d91997-04-29 20:08:16 +00001237static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001238min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1241 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 if (PyTuple_Size(args) > 1)
1244 v = args;
1245 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1246 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1249 keyfunc = PyDict_GetItemString(kwds, "key");
1250 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1251 PyErr_Format(PyExc_TypeError,
1252 "%s() got an unexpected keyword argument", name);
1253 return NULL;
1254 }
1255 Py_INCREF(keyfunc);
1256 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 it = PyObject_GetIter(v);
1259 if (it == NULL) {
1260 Py_XDECREF(keyfunc);
1261 return NULL;
1262 }
Tim Petersc3074532001-05-03 07:00:32 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 maxitem = NULL; /* the result */
1265 maxval = NULL; /* the value associated with the result */
1266 while (( item = PyIter_Next(it) )) {
1267 /* get the value from the key function */
1268 if (keyfunc != NULL) {
1269 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1270 if (val == NULL)
1271 goto Fail_it_item;
1272 }
1273 /* no key function; the value is the item */
1274 else {
1275 val = item;
1276 Py_INCREF(val);
1277 }
Tim Petersc3074532001-05-03 07:00:32 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 /* maximum value and item are unset; set them */
1280 if (maxval == NULL) {
1281 maxitem = item;
1282 maxval = val;
1283 }
1284 /* maximum value and item are set; update them as necessary */
1285 else {
1286 int cmp = PyObject_RichCompareBool(val, maxval, op);
1287 if (cmp < 0)
1288 goto Fail_it_item_and_val;
1289 else if (cmp > 0) {
1290 Py_DECREF(maxval);
1291 Py_DECREF(maxitem);
1292 maxval = val;
1293 maxitem = item;
1294 }
1295 else {
1296 Py_DECREF(item);
1297 Py_DECREF(val);
1298 }
1299 }
1300 }
1301 if (PyErr_Occurred())
1302 goto Fail_it;
1303 if (maxval == NULL) {
1304 PyErr_Format(PyExc_ValueError,
1305 "%s() arg is an empty sequence", name);
1306 assert(maxitem == NULL);
1307 }
1308 else
1309 Py_DECREF(maxval);
1310 Py_DECREF(it);
1311 Py_XDECREF(keyfunc);
1312 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001313
1314Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001316Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001318Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 Py_XDECREF(maxval);
1320 Py_XDECREF(maxitem);
1321 Py_DECREF(it);
1322 Py_XDECREF(keyfunc);
1323 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001324}
1325
Guido van Rossum79f25d91997-04-29 20:08:16 +00001326static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001327builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001330}
1331
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001332PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001333"min(iterable[, key=func]) -> value\n\
1334min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001335\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001336With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001337With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001338
1339
Guido van Rossum79f25d91997-04-29 20:08:16 +00001340static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001341builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001344}
1345
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001346PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001347"max(iterable[, key=func]) -> value\n\
1348max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001349\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001350With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001351With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001352
1353
Guido van Rossum79f25d91997-04-29 20:08:16 +00001354static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001355builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001358}
1359
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001360PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001361"oct(number) -> string\n\
1362\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001363Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001364
1365
Guido van Rossum79f25d91997-04-29 20:08:16 +00001366static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001367builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 long ord;
1370 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 if (PyBytes_Check(obj)) {
1373 size = PyBytes_GET_SIZE(obj);
1374 if (size == 1) {
1375 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1376 return PyLong_FromLong(ord);
1377 }
1378 }
1379 else if (PyUnicode_Check(obj)) {
1380 size = PyUnicode_GET_SIZE(obj);
1381 if (size == 1) {
1382 ord = (long)*PyUnicode_AS_UNICODE(obj);
1383 return PyLong_FromLong(ord);
1384 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001385#ifndef Py_UNICODE_WIDE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 if (size == 2) {
1387 /* Decode a valid surrogate pair */
1388 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1389 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1390 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1391 0xDC00 <= c1 && c1 <= 0xDFFF) {
1392 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1393 0x00010000);
1394 return PyLong_FromLong(ord);
1395 }
1396 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001397#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 }
1399 else if (PyByteArray_Check(obj)) {
1400 /* XXX Hopefully this is temporary */
1401 size = PyByteArray_GET_SIZE(obj);
1402 if (size == 1) {
1403 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1404 return PyLong_FromLong(ord);
1405 }
1406 }
1407 else {
1408 PyErr_Format(PyExc_TypeError,
1409 "ord() expected string of length 1, but " \
1410 "%.200s found", obj->ob_type->tp_name);
1411 return NULL;
1412 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 PyErr_Format(PyExc_TypeError,
1415 "ord() expected a character, "
1416 "but string of length %zd found",
1417 size);
1418 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001419}
1420
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001421PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001422"ord(c) -> integer\n\
1423\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001424Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001425)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001426#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001427PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001428"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001429)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001430#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001431;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001432
1433
Guido van Rossum79f25d91997-04-29 20:08:16 +00001434static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001435builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1440 return NULL;
1441 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001442}
1443
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001444PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001445"pow(x, y[, z]) -> number\n\
1446\n\
1447With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001448equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001449
1450
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001451
Guido van Rossum34343512006-11-30 22:13:52 +00001452static PyObject *
1453builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 static char *kwlist[] = {"sep", "end", "file", 0};
1456 static PyObject *dummy_args;
1457 PyObject *sep = NULL, *end = NULL, *file = NULL;
1458 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 if (dummy_args == NULL) {
1461 if (!(dummy_args = PyTuple_New(0)))
1462 return NULL;
1463 }
1464 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1465 kwlist, &sep, &end, &file))
1466 return NULL;
1467 if (file == NULL || file == Py_None) {
1468 file = PySys_GetObject("stdout");
1469 /* sys.stdout may be None when FILE* stdout isn't connected */
1470 if (file == Py_None)
1471 Py_RETURN_NONE;
1472 }
Guido van Rossum34343512006-11-30 22:13:52 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 if (sep == Py_None) {
1475 sep = NULL;
1476 }
1477 else if (sep && !PyUnicode_Check(sep)) {
1478 PyErr_Format(PyExc_TypeError,
1479 "sep must be None or a string, not %.200s",
1480 sep->ob_type->tp_name);
1481 return NULL;
1482 }
1483 if (end == Py_None) {
1484 end = NULL;
1485 }
1486 else if (end && !PyUnicode_Check(end)) {
1487 PyErr_Format(PyExc_TypeError,
1488 "end must be None or a string, not %.200s",
1489 end->ob_type->tp_name);
1490 return NULL;
1491 }
Guido van Rossum34343512006-11-30 22:13:52 +00001492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 for (i = 0; i < PyTuple_Size(args); i++) {
1494 if (i > 0) {
1495 if (sep == NULL)
1496 err = PyFile_WriteString(" ", file);
1497 else
1498 err = PyFile_WriteObject(sep, file,
1499 Py_PRINT_RAW);
1500 if (err)
1501 return NULL;
1502 }
1503 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1504 Py_PRINT_RAW);
1505 if (err)
1506 return NULL;
1507 }
Guido van Rossum34343512006-11-30 22:13:52 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 if (end == NULL)
1510 err = PyFile_WriteString("\n", file);
1511 else
1512 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1513 if (err)
1514 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001517}
1518
1519PyDoc_STRVAR(print_doc,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001520"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001521\n\
1522Prints the values to a stream, or to sys.stdout by default.\n\
1523Optional keyword arguments:\n\
1524file: a file-like object (stream); defaults to the current sys.stdout.\n\
1525sep: string inserted between values, default a space.\n\
1526end: string appended after the last value, default a newline.");
1527
1528
Guido van Rossuma88a0332007-02-26 16:59:55 +00001529static PyObject *
1530builtin_input(PyObject *self, PyObject *args)
1531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 PyObject *promptarg = NULL;
1533 PyObject *fin = PySys_GetObject("stdin");
1534 PyObject *fout = PySys_GetObject("stdout");
1535 PyObject *ferr = PySys_GetObject("stderr");
1536 PyObject *tmp;
1537 long fd;
1538 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 /* Parse arguments */
1541 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1542 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 /* Check that stdin/out/err are intact */
1545 if (fin == NULL || fin == Py_None) {
1546 PyErr_SetString(PyExc_RuntimeError,
1547 "input(): lost sys.stdin");
1548 return NULL;
1549 }
1550 if (fout == NULL || fout == Py_None) {
1551 PyErr_SetString(PyExc_RuntimeError,
1552 "input(): lost sys.stdout");
1553 return NULL;
1554 }
1555 if (ferr == NULL || ferr == Py_None) {
1556 PyErr_SetString(PyExc_RuntimeError,
1557 "input(): lost sys.stderr");
1558 return NULL;
1559 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 /* First of all, flush stderr */
1562 tmp = PyObject_CallMethod(ferr, "flush", "");
1563 if (tmp == NULL)
1564 PyErr_Clear();
1565 else
1566 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 /* We should only use (GNU) readline if Python's sys.stdin and
1569 sys.stdout are the same as C's stdin and stdout, because we
1570 need to pass it those. */
1571 tmp = PyObject_CallMethod(fin, "fileno", "");
1572 if (tmp == NULL) {
1573 PyErr_Clear();
1574 tty = 0;
1575 }
1576 else {
1577 fd = PyLong_AsLong(tmp);
1578 Py_DECREF(tmp);
1579 if (fd < 0 && PyErr_Occurred())
1580 return NULL;
1581 tty = fd == fileno(stdin) && isatty(fd);
1582 }
1583 if (tty) {
1584 tmp = PyObject_CallMethod(fout, "fileno", "");
1585 if (tmp == NULL)
1586 PyErr_Clear();
1587 else {
1588 fd = PyLong_AsLong(tmp);
1589 Py_DECREF(tmp);
1590 if (fd < 0 && PyErr_Occurred())
1591 return NULL;
1592 tty = fd == fileno(stdout) && isatty(fd);
1593 }
1594 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 /* If we're interactive, use (GNU) readline */
1597 if (tty) {
1598 PyObject *po;
1599 char *prompt;
1600 char *s;
1601 PyObject *stdin_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001602 char *stdin_encoding_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 PyObject *result;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1606 if (!stdin_encoding)
1607 /* stdin is a text stream, so it must have an
1608 encoding. */
1609 return NULL;
Victor Stinner306f0102010-05-19 01:06:22 +00001610 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
1611 if (stdin_encoding_str == NULL) {
1612 Py_DECREF(stdin_encoding);
1613 return NULL;
1614 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 tmp = PyObject_CallMethod(fout, "flush", "");
1616 if (tmp == NULL)
1617 PyErr_Clear();
1618 else
1619 Py_DECREF(tmp);
1620 if (promptarg != NULL) {
1621 PyObject *stringpo;
1622 PyObject *stdout_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001623 char *stdout_encoding_str;
1624 stdout_encoding = PyObject_GetAttrString(fout, "encoding");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 if (stdout_encoding == NULL) {
1626 Py_DECREF(stdin_encoding);
1627 return NULL;
1628 }
Victor Stinner306f0102010-05-19 01:06:22 +00001629 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
1630 if (stdout_encoding_str == NULL) {
1631 Py_DECREF(stdin_encoding);
1632 Py_DECREF(stdout_encoding);
1633 return NULL;
1634 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 stringpo = PyObject_Str(promptarg);
1636 if (stringpo == NULL) {
1637 Py_DECREF(stdin_encoding);
1638 Py_DECREF(stdout_encoding);
1639 return NULL;
1640 }
1641 po = PyUnicode_AsEncodedString(stringpo,
Victor Stinner306f0102010-05-19 01:06:22 +00001642 stdout_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 Py_DECREF(stdout_encoding);
1644 Py_DECREF(stringpo);
1645 if (po == NULL) {
1646 Py_DECREF(stdin_encoding);
1647 return NULL;
1648 }
1649 prompt = PyBytes_AsString(po);
1650 if (prompt == NULL) {
1651 Py_DECREF(stdin_encoding);
1652 Py_DECREF(po);
1653 return NULL;
1654 }
1655 }
1656 else {
1657 po = NULL;
1658 prompt = "";
1659 }
1660 s = PyOS_Readline(stdin, stdout, prompt);
1661 Py_XDECREF(po);
1662 if (s == NULL) {
1663 if (!PyErr_Occurred())
1664 PyErr_SetNone(PyExc_KeyboardInterrupt);
1665 Py_DECREF(stdin_encoding);
1666 return NULL;
1667 }
1668 if (*s == '\0') {
1669 PyErr_SetNone(PyExc_EOFError);
1670 result = NULL;
1671 }
1672 else { /* strip trailing '\n' */
1673 size_t len = strlen(s);
1674 if (len > PY_SSIZE_T_MAX) {
1675 PyErr_SetString(PyExc_OverflowError,
1676 "input: input too long");
1677 result = NULL;
1678 }
1679 else {
Victor Stinner306f0102010-05-19 01:06:22 +00001680 result = PyUnicode_Decode(s, len-1, stdin_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 }
1682 }
1683 Py_DECREF(stdin_encoding);
1684 PyMem_FREE(s);
1685 return result;
1686 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 /* Fallback if we're not interactive */
1689 if (promptarg != NULL) {
1690 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1691 return NULL;
1692 }
1693 tmp = PyObject_CallMethod(fout, "flush", "");
1694 if (tmp == NULL)
1695 PyErr_Clear();
1696 else
1697 Py_DECREF(tmp);
1698 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001699}
1700
1701PyDoc_STRVAR(input_doc,
1702"input([prompt]) -> string\n\
1703\n\
1704Read a string from standard input. The trailing newline is stripped.\n\
1705If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1706On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1707is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001708
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001709
Guido van Rossum79f25d91997-04-29 20:08:16 +00001710static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001711builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001714}
1715
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001716PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001717"repr(object) -> string\n\
1718\n\
1719Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001720For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001721
1722
Guido van Rossum79f25d91997-04-29 20:08:16 +00001723static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001724builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 static PyObject *round_str = NULL;
1727 PyObject *ndigits = NULL;
1728 static char *kwlist[] = {"number", "ndigits", 0};
1729 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1732 kwlist, &number, &ndigits))
1733 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 if (Py_TYPE(number)->tp_dict == NULL) {
1736 if (PyType_Ready(Py_TYPE(number)) < 0)
1737 return NULL;
1738 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 if (round_str == NULL) {
1741 round_str = PyUnicode_InternFromString("__round__");
1742 if (round_str == NULL)
1743 return NULL;
1744 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 round = _PyType_Lookup(Py_TYPE(number), round_str);
1747 if (round == NULL) {
1748 PyErr_Format(PyExc_TypeError,
1749 "type %.100s doesn't define __round__ method",
1750 Py_TYPE(number)->tp_name);
1751 return NULL;
1752 }
Alex Martelliae211f92007-08-22 23:21:33 +00001753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 if (ndigits == NULL)
1755 return PyObject_CallFunction(round, "O", number);
1756 else
1757 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001758}
1759
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001760PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001761"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001762\n\
1763Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001764This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001765same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001766
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001767
Raymond Hettinger64958a12003-12-17 20:43:33 +00001768static PyObject *
1769builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1772 PyObject *callable;
1773 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1774 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 /* args 1-3 should match listsort in Objects/listobject.c */
1777 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1778 kwlist, &seq, &keyfunc, &reverse))
1779 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 newlist = PySequence_List(seq);
1782 if (newlist == NULL)
1783 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 callable = PyObject_GetAttrString(newlist, "sort");
1786 if (callable == NULL) {
1787 Py_DECREF(newlist);
1788 return NULL;
1789 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 newargs = PyTuple_GetSlice(args, 1, 4);
1792 if (newargs == NULL) {
1793 Py_DECREF(newlist);
1794 Py_DECREF(callable);
1795 return NULL;
1796 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 v = PyObject_Call(callable, newargs, kwds);
1799 Py_DECREF(newargs);
1800 Py_DECREF(callable);
1801 if (v == NULL) {
1802 Py_DECREF(newlist);
1803 return NULL;
1804 }
1805 Py_DECREF(v);
1806 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001807}
1808
1809PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001810"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001811
Guido van Rossum79f25d91997-04-29 20:08:16 +00001812static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001813builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 PyObject *v = NULL;
1816 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1819 return NULL;
1820 if (v == NULL) {
1821 d = PyEval_GetLocals();
1822 if (d == NULL) {
1823 if (!PyErr_Occurred())
1824 PyErr_SetString(PyExc_SystemError,
1825 "vars(): no locals!?");
1826 }
1827 else
1828 Py_INCREF(d);
1829 }
1830 else {
1831 d = PyObject_GetAttrString(v, "__dict__");
1832 if (d == NULL) {
1833 PyErr_SetString(PyExc_TypeError,
1834 "vars() argument must have __dict__ attribute");
1835 return NULL;
1836 }
1837 }
1838 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001839}
1840
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001841PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001842"vars([object]) -> dictionary\n\
1843\n\
1844Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001845With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001846
Alex Martellia70b1912003-04-22 08:12:33 +00001847static PyObject*
1848builtin_sum(PyObject *self, PyObject *args)
1849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 PyObject *seq;
1851 PyObject *result = NULL;
1852 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1855 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 iter = PyObject_GetIter(seq);
1858 if (iter == NULL)
1859 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 if (result == NULL) {
1862 result = PyLong_FromLong(0);
1863 if (result == NULL) {
1864 Py_DECREF(iter);
1865 return NULL;
1866 }
1867 } else {
1868 /* reject string values for 'start' parameter */
1869 if (PyUnicode_Check(result)) {
1870 PyErr_SetString(PyExc_TypeError,
1871 "sum() can't sum strings [use ''.join(seq) instead]");
1872 Py_DECREF(iter);
1873 return NULL;
1874 }
1875 if (PyByteArray_Check(result)) {
1876 PyErr_SetString(PyExc_TypeError,
1877 "sum() can't sum bytes [use b''.join(seq) instead]");
1878 Py_DECREF(iter);
1879 return NULL;
1880 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 Py_INCREF(result);
1883 }
Alex Martellia70b1912003-04-22 08:12:33 +00001884
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001885#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1887 Assumes all inputs are the same type. If the assumption fails, default
1888 to the more general routine.
1889 */
1890 if (PyLong_CheckExact(result)) {
1891 int overflow;
1892 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1893 /* If this already overflowed, don't even enter the loop. */
1894 if (overflow == 0) {
1895 Py_DECREF(result);
1896 result = NULL;
1897 }
1898 while(result == NULL) {
1899 item = PyIter_Next(iter);
1900 if (item == NULL) {
1901 Py_DECREF(iter);
1902 if (PyErr_Occurred())
1903 return NULL;
1904 return PyLong_FromLong(i_result);
1905 }
1906 if (PyLong_CheckExact(item)) {
1907 long b = PyLong_AsLongAndOverflow(item, &overflow);
1908 long x = i_result + b;
1909 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1910 i_result = x;
1911 Py_DECREF(item);
1912 continue;
1913 }
1914 }
1915 /* Either overflowed or is not an int. Restore real objects and process normally */
1916 result = PyLong_FromLong(i_result);
1917 temp = PyNumber_Add(result, item);
1918 Py_DECREF(result);
1919 Py_DECREF(item);
1920 result = temp;
1921 if (result == NULL) {
1922 Py_DECREF(iter);
1923 return NULL;
1924 }
1925 }
1926 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 if (PyFloat_CheckExact(result)) {
1929 double f_result = PyFloat_AS_DOUBLE(result);
1930 Py_DECREF(result);
1931 result = NULL;
1932 while(result == NULL) {
1933 item = PyIter_Next(iter);
1934 if (item == NULL) {
1935 Py_DECREF(iter);
1936 if (PyErr_Occurred())
1937 return NULL;
1938 return PyFloat_FromDouble(f_result);
1939 }
1940 if (PyFloat_CheckExact(item)) {
1941 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1942 f_result += PyFloat_AS_DOUBLE(item);
1943 PyFPE_END_PROTECT(f_result)
1944 Py_DECREF(item);
1945 continue;
1946 }
1947 if (PyLong_CheckExact(item)) {
1948 long value;
1949 int overflow;
1950 value = PyLong_AsLongAndOverflow(item, &overflow);
1951 if (!overflow) {
1952 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1953 f_result += (double)value;
1954 PyFPE_END_PROTECT(f_result)
1955 Py_DECREF(item);
1956 continue;
1957 }
1958 }
1959 result = PyFloat_FromDouble(f_result);
1960 temp = PyNumber_Add(result, item);
1961 Py_DECREF(result);
1962 Py_DECREF(item);
1963 result = temp;
1964 if (result == NULL) {
1965 Py_DECREF(iter);
1966 return NULL;
1967 }
1968 }
1969 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001970#endif
1971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 for(;;) {
1973 item = PyIter_Next(iter);
1974 if (item == NULL) {
1975 /* error, or end-of-sequence */
1976 if (PyErr_Occurred()) {
1977 Py_DECREF(result);
1978 result = NULL;
1979 }
1980 break;
1981 }
1982 /* It's tempting to use PyNumber_InPlaceAdd instead of
1983 PyNumber_Add here, to avoid quadratic running time
1984 when doing 'sum(list_of_lists, [])'. However, this
1985 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 empty = []
1988 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00001989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 would change the value of empty. */
1991 temp = PyNumber_Add(result, item);
1992 Py_DECREF(result);
1993 Py_DECREF(item);
1994 result = temp;
1995 if (result == NULL)
1996 break;
1997 }
1998 Py_DECREF(iter);
1999 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002000}
2001
2002PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002003"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002004\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002005Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2006of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002007empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002008
2009
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002010static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002011builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 PyObject *inst;
2014 PyObject *cls;
2015 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2018 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 retval = PyObject_IsInstance(inst, cls);
2021 if (retval < 0)
2022 return NULL;
2023 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002024}
2025
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002026PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002027"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002028\n\
2029Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002030With a type as second argument, return whether that is the object's type.\n\
2031The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002032isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002033
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002034
2035static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002036builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 PyObject *derived;
2039 PyObject *cls;
2040 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2043 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 retval = PyObject_IsSubclass(derived, cls);
2046 if (retval < 0)
2047 return NULL;
2048 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002049}
2050
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002051PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002052"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002053\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002054Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2055When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2056is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002057
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002058
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002059typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 PyObject_HEAD
2061 Py_ssize_t tuplesize;
2062 PyObject *ittuple; /* tuple of iterators */
2063 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002064} zipobject;
2065
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002066static PyObject *
2067zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 zipobject *lz;
2070 Py_ssize_t i;
2071 PyObject *ittuple; /* tuple of iterators */
2072 PyObject *result;
2073 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2076 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 /* args must be a tuple */
2079 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 /* obtain iterators */
2082 ittuple = PyTuple_New(tuplesize);
2083 if (ittuple == NULL)
2084 return NULL;
2085 for (i=0; i < tuplesize; ++i) {
2086 PyObject *item = PyTuple_GET_ITEM(args, i);
2087 PyObject *it = PyObject_GetIter(item);
2088 if (it == NULL) {
2089 if (PyErr_ExceptionMatches(PyExc_TypeError))
2090 PyErr_Format(PyExc_TypeError,
2091 "zip argument #%zd must support iteration",
2092 i+1);
2093 Py_DECREF(ittuple);
2094 return NULL;
2095 }
2096 PyTuple_SET_ITEM(ittuple, i, it);
2097 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 /* create a result holder */
2100 result = PyTuple_New(tuplesize);
2101 if (result == NULL) {
2102 Py_DECREF(ittuple);
2103 return NULL;
2104 }
2105 for (i=0 ; i < tuplesize ; i++) {
2106 Py_INCREF(Py_None);
2107 PyTuple_SET_ITEM(result, i, Py_None);
2108 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 /* create zipobject structure */
2111 lz = (zipobject *)type->tp_alloc(type, 0);
2112 if (lz == NULL) {
2113 Py_DECREF(ittuple);
2114 Py_DECREF(result);
2115 return NULL;
2116 }
2117 lz->ittuple = ittuple;
2118 lz->tuplesize = tuplesize;
2119 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002122}
2123
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002124static void
2125zip_dealloc(zipobject *lz)
2126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 PyObject_GC_UnTrack(lz);
2128 Py_XDECREF(lz->ittuple);
2129 Py_XDECREF(lz->result);
2130 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002131}
2132
2133static int
2134zip_traverse(zipobject *lz, visitproc visit, void *arg)
2135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 Py_VISIT(lz->ittuple);
2137 Py_VISIT(lz->result);
2138 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002139}
2140
2141static PyObject *
2142zip_next(zipobject *lz)
2143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 Py_ssize_t i;
2145 Py_ssize_t tuplesize = lz->tuplesize;
2146 PyObject *result = lz->result;
2147 PyObject *it;
2148 PyObject *item;
2149 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 if (tuplesize == 0)
2152 return NULL;
2153 if (Py_REFCNT(result) == 1) {
2154 Py_INCREF(result);
2155 for (i=0 ; i < tuplesize ; i++) {
2156 it = PyTuple_GET_ITEM(lz->ittuple, i);
2157 item = (*Py_TYPE(it)->tp_iternext)(it);
2158 if (item == NULL) {
2159 Py_DECREF(result);
2160 return NULL;
2161 }
2162 olditem = PyTuple_GET_ITEM(result, i);
2163 PyTuple_SET_ITEM(result, i, item);
2164 Py_DECREF(olditem);
2165 }
2166 } else {
2167 result = PyTuple_New(tuplesize);
2168 if (result == NULL)
2169 return NULL;
2170 for (i=0 ; i < tuplesize ; i++) {
2171 it = PyTuple_GET_ITEM(lz->ittuple, i);
2172 item = (*Py_TYPE(it)->tp_iternext)(it);
2173 if (item == NULL) {
2174 Py_DECREF(result);
2175 return NULL;
2176 }
2177 PyTuple_SET_ITEM(result, i, item);
2178 }
2179 }
2180 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002181}
Barry Warsawbd599b52000-08-03 15:45:29 +00002182
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002183PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002184"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002185\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002186Return a zip object whose .__next__() method returns a tuple where\n\
2187the i-th element comes from the i-th iterable argument. The .__next__()\n\
2188method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002189is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002190
2191PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2193 "zip", /* tp_name */
2194 sizeof(zipobject), /* tp_basicsize */
2195 0, /* tp_itemsize */
2196 /* methods */
2197 (destructor)zip_dealloc, /* tp_dealloc */
2198 0, /* tp_print */
2199 0, /* tp_getattr */
2200 0, /* tp_setattr */
2201 0, /* tp_reserved */
2202 0, /* tp_repr */
2203 0, /* tp_as_number */
2204 0, /* tp_as_sequence */
2205 0, /* tp_as_mapping */
2206 0, /* tp_hash */
2207 0, /* tp_call */
2208 0, /* tp_str */
2209 PyObject_GenericGetAttr, /* tp_getattro */
2210 0, /* tp_setattro */
2211 0, /* tp_as_buffer */
2212 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2213 Py_TPFLAGS_BASETYPE, /* tp_flags */
2214 zip_doc, /* tp_doc */
2215 (traverseproc)zip_traverse, /* tp_traverse */
2216 0, /* tp_clear */
2217 0, /* tp_richcompare */
2218 0, /* tp_weaklistoffset */
2219 PyObject_SelfIter, /* tp_iter */
2220 (iternextfunc)zip_next, /* tp_iternext */
2221 0, /* tp_methods */
2222 0, /* tp_members */
2223 0, /* tp_getset */
2224 0, /* tp_base */
2225 0, /* tp_dict */
2226 0, /* tp_descr_get */
2227 0, /* tp_descr_set */
2228 0, /* tp_dictoffset */
2229 0, /* tp_init */
2230 PyType_GenericAlloc, /* tp_alloc */
2231 zip_new, /* tp_new */
2232 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002233};
Barry Warsawbd599b52000-08-03 15:45:29 +00002234
2235
Guido van Rossum79f25d91997-04-29 20:08:16 +00002236static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 {"__build_class__", (PyCFunction)builtin___build_class__,
2238 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2239 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2240 {"abs", builtin_abs, METH_O, abs_doc},
2241 {"all", builtin_all, METH_O, all_doc},
2242 {"any", builtin_any, METH_O, any_doc},
2243 {"ascii", builtin_ascii, METH_O, ascii_doc},
2244 {"bin", builtin_bin, METH_O, bin_doc},
2245 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2246 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2247 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2248 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2249 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2250 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2251 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2252 {"format", builtin_format, METH_VARARGS, format_doc},
2253 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2254 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2255 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2256 {"hash", builtin_hash, METH_O, hash_doc},
2257 {"hex", builtin_hex, METH_O, hex_doc},
2258 {"id", builtin_id, METH_O, id_doc},
2259 {"input", builtin_input, METH_VARARGS, input_doc},
2260 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2261 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2262 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2263 {"len", builtin_len, METH_O, len_doc},
2264 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2265 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2266 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2267 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2268 {"oct", builtin_oct, METH_O, oct_doc},
2269 {"ord", builtin_ord, METH_O, ord_doc},
2270 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2271 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2272 {"repr", builtin_repr, METH_O, repr_doc},
2273 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2274 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2275 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2276 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2277 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2278 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002279};
2280
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002281PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002282"Built-in functions, exceptions, and other objects.\n\
2283\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002284Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002285
Martin v. Löwis1a214512008-06-11 05:26:20 +00002286static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 PyModuleDef_HEAD_INIT,
2288 "builtins",
2289 builtin_doc,
2290 -1, /* multiple "initialization" just copies the module dict. */
2291 builtin_methods,
2292 NULL,
2293 NULL,
2294 NULL,
2295 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002296};
2297
2298
Guido van Rossum25ce5661997-08-02 03:10:38 +00002299PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002300_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 PyObject *mod, *dict, *debug;
2303 mod = PyModule_Create(&builtinsmodule);
2304 if (mod == NULL)
2305 return NULL;
2306 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002307
Tim Peters7571a0f2003-03-23 17:52:28 +00002308#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 /* "builtins" exposes a number of statically allocated objects
2310 * that, before this code was added in 2.3, never showed up in
2311 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2312 * result, programs leaking references to None and False (etc)
2313 * couldn't be diagnosed by examining sys.getobjects(0).
2314 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002315#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2316#else
2317#define ADD_TO_ALL(OBJECT) (void)0
2318#endif
2319
Tim Peters4b7625e2001-09-13 21:37:17 +00002320#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2322 return NULL; \
2323 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 SETBUILTIN("None", Py_None);
2326 SETBUILTIN("Ellipsis", Py_Ellipsis);
2327 SETBUILTIN("NotImplemented", Py_NotImplemented);
2328 SETBUILTIN("False", Py_False);
2329 SETBUILTIN("True", Py_True);
2330 SETBUILTIN("bool", &PyBool_Type);
2331 SETBUILTIN("memoryview", &PyMemoryView_Type);
2332 SETBUILTIN("bytearray", &PyByteArray_Type);
2333 SETBUILTIN("bytes", &PyBytes_Type);
2334 SETBUILTIN("classmethod", &PyClassMethod_Type);
2335 SETBUILTIN("complex", &PyComplex_Type);
2336 SETBUILTIN("dict", &PyDict_Type);
2337 SETBUILTIN("enumerate", &PyEnum_Type);
2338 SETBUILTIN("filter", &PyFilter_Type);
2339 SETBUILTIN("float", &PyFloat_Type);
2340 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2341 SETBUILTIN("property", &PyProperty_Type);
2342 SETBUILTIN("int", &PyLong_Type);
2343 SETBUILTIN("list", &PyList_Type);
2344 SETBUILTIN("map", &PyMap_Type);
2345 SETBUILTIN("object", &PyBaseObject_Type);
2346 SETBUILTIN("range", &PyRange_Type);
2347 SETBUILTIN("reversed", &PyReversed_Type);
2348 SETBUILTIN("set", &PySet_Type);
2349 SETBUILTIN("slice", &PySlice_Type);
2350 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2351 SETBUILTIN("str", &PyUnicode_Type);
2352 SETBUILTIN("super", &PySuper_Type);
2353 SETBUILTIN("tuple", &PyTuple_Type);
2354 SETBUILTIN("type", &PyType_Type);
2355 SETBUILTIN("zip", &PyZip_Type);
2356 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2357 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2358 Py_XDECREF(debug);
2359 return NULL;
2360 }
2361 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002364#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002365#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002366}