blob: f300ab2a7b057624f6f9113c79da4d2045b18968 [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 Rossum3f5da241990-12-20 15:06:42 +00008
Guido van Rossum6bf62da1997-04-11 20:37:35 +00009#include <ctype.h>
10
Victor Stinnerb744ba12010-05-15 12:27:16 +000011#ifdef HAVE_LANGINFO_H
12#include <langinfo.h> /* CODESET */
13#endif
14
Mark Hammond26cffde42001-05-14 12:17:34 +000015/* The default encoding used by the platform file system APIs
16 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000017
18 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
19 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000020*/
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000021#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Mark Hammond26cffde42001-05-14 12:17:34 +000022const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000023int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000024#elif defined(__APPLE__)
25const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerb744ba12010-05-15 12:27:16 +000027#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
28const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int Py_HasFileSystemDefaultEncoding = 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +000030#else
31const char *Py_FileSystemDefaultEncoding = "utf-8";
32int Py_HasFileSystemDefaultEncoding = 1;
Mark Hammond26cffde42001-05-14 12:17:34 +000033#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000034
Guido van Rossum79f25d91997-04-29 20:08:16 +000035static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000036builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
37{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000038 PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell;
39 PyObject *cls = NULL;
40 Py_ssize_t nargs, nbases;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 assert(args != NULL);
43 if (!PyTuple_Check(args)) {
44 PyErr_SetString(PyExc_TypeError,
45 "__build_class__: args is not a tuple");
46 return NULL;
47 }
48 nargs = PyTuple_GET_SIZE(args);
49 if (nargs < 2) {
50 PyErr_SetString(PyExc_TypeError,
51 "__build_class__: not enough arguments");
52 return NULL;
53 }
54 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
55 name = PyTuple_GET_ITEM(args, 1);
56 if (!PyUnicode_Check(name)) {
57 PyErr_SetString(PyExc_TypeError,
58 "__build_class__: name is not a string");
59 return NULL;
60 }
61 bases = PyTuple_GetSlice(args, 2, nargs);
62 if (bases == NULL)
63 return NULL;
64 nbases = nargs - 2;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000066 if (kwds == NULL) {
67 meta = NULL;
68 mkw = NULL;
69 }
70 else {
71 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
72 if (mkw == NULL) {
73 Py_DECREF(bases);
74 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000075 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 meta = PyDict_GetItemString(mkw, "metaclass");
77 if (meta != NULL) {
78 Py_INCREF(meta);
79 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
80 Py_DECREF(meta);
81 Py_DECREF(mkw);
82 Py_DECREF(bases);
83 return NULL;
84 }
85 }
86 }
87 if (meta == NULL) {
88 if (PyTuple_GET_SIZE(bases) == 0)
89 meta = (PyObject *) (&PyType_Type);
90 else {
91 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
92 meta = (PyObject *) (base0->ob_type);
93 }
94 Py_INCREF(meta);
95 }
96 prep = PyObject_GetAttrString(meta, "__prepare__");
97 if (prep == NULL) {
98 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
99 PyErr_Clear();
100 ns = PyDict_New();
101 }
102 else {
103 Py_DECREF(meta);
104 Py_XDECREF(mkw);
105 Py_DECREF(bases);
106 return NULL;
107 }
108 }
109 else {
110 PyObject *pargs = PyTuple_Pack(2, name, bases);
111 if (pargs == NULL) {
112 Py_DECREF(prep);
113 Py_DECREF(meta);
114 Py_XDECREF(mkw);
115 Py_DECREF(bases);
116 return NULL;
117 }
118 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
119 Py_DECREF(pargs);
120 Py_DECREF(prep);
121 }
122 if (ns == NULL) {
123 Py_DECREF(meta);
124 Py_XDECREF(mkw);
125 Py_DECREF(bases);
126 return NULL;
127 }
128 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
129 if (cell != NULL) {
130 PyObject *margs;
131 margs = PyTuple_Pack(3, name, bases, ns);
132 if (margs != NULL) {
133 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
134 Py_DECREF(margs);
135 }
136 if (cls != NULL && PyCell_Check(cell)) {
137 Py_INCREF(cls);
138 PyCell_SET(cell, cls);
139 }
140 Py_DECREF(cell);
141 }
142 Py_DECREF(ns);
143 Py_DECREF(meta);
144 Py_XDECREF(mkw);
145 Py_DECREF(bases);
146 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000147}
148
149PyDoc_STRVAR(build_class_doc,
150"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
151\n\
152Internal helper function used by the class statement.");
153
154static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000155builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
158 "level", 0};
159 char *name;
160 PyObject *globals = NULL;
161 PyObject *locals = NULL;
162 PyObject *fromlist = NULL;
163 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
166 kwlist, &name, &globals, &locals, &fromlist, &level))
167 return NULL;
168 return PyImport_ImportModuleLevel(name, globals, locals,
169 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000170}
171
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000172PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000173"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000174\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000175Import a module. Because this function is meant for use by the Python\n\
176interpreter and not for general use it is better to use\n\
177importlib.import_module() to programmatically import a module.\n\
178\n\
179The globals argument is only used to determine the context;\n\
180they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000181should be a list of names to emulate ``from name import ...'', or an\n\
182empty list to emulate ``import name''.\n\
183When importing a module from a package, note that __import__('A.B', ...)\n\
184returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000185fromlist is not empty. Level is used to determine whether to perform \n\
186absolute or relative imports. -1 is the original strategy of attempting\n\
187both absolute and relative imports, 0 is absolute, a positive number\n\
188is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000189
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000190
Guido van Rossum79f25d91997-04-29 20:08:16 +0000191static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000192builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000195}
196
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000197PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000198"abs(number) -> number\n\
199\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000200Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000201
Raymond Hettinger96229b12005-03-11 06:49:40 +0000202static PyObject *
203builtin_all(PyObject *self, PyObject *v)
204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 PyObject *it, *item;
206 PyObject *(*iternext)(PyObject *);
207 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 it = PyObject_GetIter(v);
210 if (it == NULL)
211 return NULL;
212 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 for (;;) {
215 item = iternext(it);
216 if (item == NULL)
217 break;
218 cmp = PyObject_IsTrue(item);
219 Py_DECREF(item);
220 if (cmp < 0) {
221 Py_DECREF(it);
222 return NULL;
223 }
224 if (cmp == 0) {
225 Py_DECREF(it);
226 Py_RETURN_FALSE;
227 }
228 }
229 Py_DECREF(it);
230 if (PyErr_Occurred()) {
231 if (PyErr_ExceptionMatches(PyExc_StopIteration))
232 PyErr_Clear();
233 else
234 return NULL;
235 }
236 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000237}
238
239PyDoc_STRVAR(all_doc,
240"all(iterable) -> bool\n\
241\n\
242Return True if bool(x) is True for all values x in the iterable.");
243
244static PyObject *
245builtin_any(PyObject *self, PyObject *v)
246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 PyObject *it, *item;
248 PyObject *(*iternext)(PyObject *);
249 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 it = PyObject_GetIter(v);
252 if (it == NULL)
253 return NULL;
254 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 for (;;) {
257 item = iternext(it);
258 if (item == NULL)
259 break;
260 cmp = PyObject_IsTrue(item);
261 Py_DECREF(item);
262 if (cmp < 0) {
263 Py_DECREF(it);
264 return NULL;
265 }
266 if (cmp == 1) {
267 Py_DECREF(it);
268 Py_RETURN_TRUE;
269 }
270 }
271 Py_DECREF(it);
272 if (PyErr_Occurred()) {
273 if (PyErr_ExceptionMatches(PyExc_StopIteration))
274 PyErr_Clear();
275 else
276 return NULL;
277 }
278 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000279}
280
281PyDoc_STRVAR(any_doc,
282"any(iterable) -> bool\n\
283\n\
284Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000285
Georg Brandl559e5d72008-06-11 18:37:52 +0000286static PyObject *
287builtin_ascii(PyObject *self, PyObject *v)
288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000290}
291
292PyDoc_STRVAR(ascii_doc,
293"ascii(object) -> string\n\
294\n\
295As repr(), return a string containing a printable representation of an\n\
296object, but escape the non-ASCII characters in the string returned by\n\
297repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
298to that returned by repr() in Python 2.");
299
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000300
Guido van Rossum79f25d91997-04-29 20:08:16 +0000301static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000302builtin_bin(PyObject *self, PyObject *v)
303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000305}
306
307PyDoc_STRVAR(bin_doc,
308"bin(number) -> string\n\
309\n\
310Return the binary representation of an integer or long integer.");
311
312
Antoine Pitroue71362d2010-11-27 22:00:11 +0000313static PyObject *
314builtin_callable(PyObject *self, PyObject *v)
315{
316 return PyBool_FromLong((long)PyCallable_Check(v));
317}
318
319PyDoc_STRVAR(callable_doc,
320"callable(object) -> bool\n\
321\n\
322Return whether the object is callable (i.e., some kind of function).\n\
323Note that classes are callable, as are instances of classes with a\n\
324__call__() method.");
325
326
Raymond Hettinger17301e92008-03-13 00:19:26 +0000327typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 PyObject_HEAD
329 PyObject *func;
330 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000331} filterobject;
332
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000333static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000334filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 PyObject *func, *seq;
337 PyObject *it;
338 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
341 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
344 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 /* Get iterator. */
347 it = PyObject_GetIter(seq);
348 if (it == NULL)
349 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 /* create filterobject structure */
352 lz = (filterobject *)type->tp_alloc(type, 0);
353 if (lz == NULL) {
354 Py_DECREF(it);
355 return NULL;
356 }
357 Py_INCREF(func);
358 lz->func = func;
359 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000362}
363
364static void
365filter_dealloc(filterobject *lz)
366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 PyObject_GC_UnTrack(lz);
368 Py_XDECREF(lz->func);
369 Py_XDECREF(lz->it);
370 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000371}
372
373static int
374filter_traverse(filterobject *lz, visitproc visit, void *arg)
375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 Py_VISIT(lz->it);
377 Py_VISIT(lz->func);
378 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000379}
380
381static PyObject *
382filter_next(filterobject *lz)
383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 PyObject *item;
385 PyObject *it = lz->it;
386 long ok;
387 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 iternext = *Py_TYPE(it)->tp_iternext;
390 for (;;) {
391 item = iternext(it);
392 if (item == NULL)
393 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
396 ok = PyObject_IsTrue(item);
397 } else {
398 PyObject *good;
399 good = PyObject_CallFunctionObjArgs(lz->func,
400 item, NULL);
401 if (good == NULL) {
402 Py_DECREF(item);
403 return NULL;
404 }
405 ok = PyObject_IsTrue(good);
406 Py_DECREF(good);
407 }
408 if (ok)
409 return item;
410 Py_DECREF(item);
411 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000412}
413
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000414PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000415"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000416\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000417Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000418is true. If function is None, return the items that are true.");
419
420PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 PyVarObject_HEAD_INIT(&PyType_Type, 0)
422 "filter", /* tp_name */
423 sizeof(filterobject), /* tp_basicsize */
424 0, /* tp_itemsize */
425 /* methods */
426 (destructor)filter_dealloc, /* tp_dealloc */
427 0, /* tp_print */
428 0, /* tp_getattr */
429 0, /* tp_setattr */
430 0, /* tp_reserved */
431 0, /* tp_repr */
432 0, /* tp_as_number */
433 0, /* tp_as_sequence */
434 0, /* tp_as_mapping */
435 0, /* tp_hash */
436 0, /* tp_call */
437 0, /* tp_str */
438 PyObject_GenericGetAttr, /* tp_getattro */
439 0, /* tp_setattro */
440 0, /* tp_as_buffer */
441 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
442 Py_TPFLAGS_BASETYPE, /* tp_flags */
443 filter_doc, /* tp_doc */
444 (traverseproc)filter_traverse, /* tp_traverse */
445 0, /* tp_clear */
446 0, /* tp_richcompare */
447 0, /* tp_weaklistoffset */
448 PyObject_SelfIter, /* tp_iter */
449 (iternextfunc)filter_next, /* tp_iternext */
450 0, /* tp_methods */
451 0, /* tp_members */
452 0, /* tp_getset */
453 0, /* tp_base */
454 0, /* tp_dict */
455 0, /* tp_descr_get */
456 0, /* tp_descr_set */
457 0, /* tp_dictoffset */
458 0, /* tp_init */
459 PyType_GenericAlloc, /* tp_alloc */
460 filter_new, /* tp_new */
461 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000462};
463
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000464
Eric Smith8c663262007-08-25 02:26:07 +0000465static PyObject *
466builtin_format(PyObject *self, PyObject *args)
467{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000468 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000469 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000470
Eric Smith8fd3eba2008-02-17 19:48:00 +0000471 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000473
Eric Smith8fd3eba2008-02-17 19:48:00 +0000474 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000475}
476
Eric Smith8c663262007-08-25 02:26:07 +0000477PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000478"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000479\n\
Eric Smith81936692007-08-31 01:14:01 +0000480Returns value.__format__(format_spec)\n\
481format_spec defaults to \"\"");
482
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000483static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000484builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 if (!PyArg_ParseTuple(args, "i:chr", &x))
489 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000492}
493
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000494PyDoc_VAR(chr_doc) = PyDoc_STR(
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000495"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000496\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000497Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000498)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000499#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000500PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000501"\nIf 0x10000 <= i, a surrogate pair is returned."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000502)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000503#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000504;
Guido van Rossum09095f32000-03-10 23:00:52 +0000505
506
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000507static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000508source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 char *str;
511 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 if (PyUnicode_Check(cmd)) {
514 cf->cf_flags |= PyCF_IGNORE_COOKIE;
515 cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL);
516 if (cmd == NULL)
517 return NULL;
518 }
519 else if (!PyObject_CheckReadBuffer(cmd)) {
520 PyErr_Format(PyExc_TypeError,
521 "%s() arg 1 must be a %s object",
522 funcname, what);
523 return NULL;
524 }
525 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
526 return NULL;
527 }
528 if (strlen(str) != size) {
529 PyErr_SetString(PyExc_TypeError,
530 "source code string cannot contain null bytes");
531 return NULL;
532 }
533 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000534}
535
Guido van Rossum79f25d91997-04-29 20:08:16 +0000536static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000537builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 char *str;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000540 PyObject *filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 char *filename;
542 char *startstr;
543 int mode = -1;
544 int dont_inherit = 0;
545 int supplied_flags = 0;
546 int is_ast;
547 PyCompilerFlags cf;
548 PyObject *cmd;
549 static char *kwlist[] = {"source", "filename", "mode", "flags",
550 "dont_inherit", NULL};
551 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000552 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000553
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000554 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|ii:compile", kwlist,
555 &cmd,
556 PyUnicode_FSConverter, &filename_obj,
557 &startstr, &supplied_flags,
558 &dont_inherit))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000560
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000561 filename = PyBytes_AS_STRING(filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 if (supplied_flags &
565 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
566 {
567 PyErr_SetString(PyExc_ValueError,
568 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000569 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 }
571 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 if (!dont_inherit) {
574 PyEval_MergeCompilerFlags(&cf);
575 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 if (strcmp(startstr, "exec") == 0)
578 mode = 0;
579 else if (strcmp(startstr, "eval") == 0)
580 mode = 1;
581 else if (strcmp(startstr, "single") == 0)
582 mode = 2;
583 else {
584 PyErr_SetString(PyExc_ValueError,
585 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000586 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 is_ast = PyAST_Check(cmd);
590 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000591 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 if (supplied_flags & PyCF_ONLY_AST) {
594 Py_INCREF(cmd);
595 result = cmd;
596 }
597 else {
598 PyArena *arena;
599 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 arena = PyArena_New();
602 mod = PyAST_obj2mod(cmd, arena, mode);
603 if (mod == NULL) {
604 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000605 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 }
607 result = (PyObject*)PyAST_Compile(mod, filename,
608 &cf, arena);
609 PyArena_Free(arena);
610 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000611 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
615 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000616 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000617
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000618 result = Py_CompileStringFlags(str, filename, start[mode], &cf);
619 goto finally;
620
621error:
622 result = NULL;
623finally:
624 Py_DECREF(filename_obj);
625 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000626}
627
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000628PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000629"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000630\n\
631Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000632into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000633The filename will be used for run-time error messages.\n\
634The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000635single (interactive) statement, or 'eval' to compile an expression.\n\
636The flags argument, if present, controls which future statements influence\n\
637the compilation of the code.\n\
638The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
639the effects of any future statements in effect in the code calling\n\
640compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000641in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000642
Guido van Rossum79f25d91997-04-29 20:08:16 +0000643static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000644builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
649 return NULL;
650 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000651}
652
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000653PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000654"dir([object]) -> list of strings\n"
655"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000656"If called without an argument, return the names in the current scope.\n"
657"Else, return an alphabetized list of names comprising (some of) the attributes\n"
658"of the given object, and of attributes reachable from it.\n"
659"If the object supplies a method named __dir__, it will be used; otherwise\n"
660"the default dir() logic is used and returns:\n"
661" for a module object: the module's attributes.\n"
662" for a class object: its attributes, and recursively the attributes\n"
663" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000664" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000665" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000666
Guido van Rossum79f25d91997-04-29 20:08:16 +0000667static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000668builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
673 return NULL;
674 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000675}
676
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000677PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000678"divmod(x, y) -> (div, mod)\n\
679\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000680Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000681
682
Guido van Rossum79f25d91997-04-29 20:08:16 +0000683static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000684builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 PyObject *cmd, *result, *tmp = NULL;
687 PyObject *globals = Py_None, *locals = Py_None;
688 char *str;
689 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
692 return NULL;
693 if (locals != Py_None && !PyMapping_Check(locals)) {
694 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
695 return NULL;
696 }
697 if (globals != Py_None && !PyDict_Check(globals)) {
698 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
699 "globals must be a real dict; try eval(expr, {}, mapping)"
700 : "globals must be a dict");
701 return NULL;
702 }
703 if (globals == Py_None) {
704 globals = PyEval_GetGlobals();
705 if (locals == Py_None)
706 locals = PyEval_GetLocals();
707 }
708 else if (locals == Py_None)
709 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 if (globals == NULL || locals == NULL) {
712 PyErr_SetString(PyExc_TypeError,
713 "eval must be given globals and locals "
714 "when called without a frame");
715 return NULL;
716 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
719 if (PyDict_SetItemString(globals, "__builtins__",
720 PyEval_GetBuiltins()) != 0)
721 return NULL;
722 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 if (PyCode_Check(cmd)) {
725 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
726 PyErr_SetString(PyExc_TypeError,
727 "code object passed to eval() may not contain free variables");
728 return NULL;
729 }
730 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
731 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
734 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
735 if (str == NULL)
736 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 while (*str == ' ' || *str == '\t')
739 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 (void)PyEval_MergeCompilerFlags(&cf);
742 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
743 Py_XDECREF(tmp);
744 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000745}
746
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000747PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000748"eval(source[, globals[, locals]]) -> value\n\
749\n\
750Evaluate the source in the context of globals and locals.\n\
751The source may be a string representing a Python expression\n\
752or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000753The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000754defaulting to the current globals and locals.\n\
755If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000756
Georg Brandl7cae87c2006-09-06 06:51:57 +0000757static PyObject *
758builtin_exec(PyObject *self, PyObject *args)
759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 PyObject *v;
761 PyObject *prog, *globals = Py_None, *locals = Py_None;
762 int plain = 0;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
765 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 if (globals == Py_None) {
768 globals = PyEval_GetGlobals();
769 if (locals == Py_None) {
770 locals = PyEval_GetLocals();
771 plain = 1;
772 }
773 if (!globals || !locals) {
774 PyErr_SetString(PyExc_SystemError,
775 "globals and locals cannot be NULL");
776 return NULL;
777 }
778 }
779 else if (locals == Py_None)
780 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 if (!PyDict_Check(globals)) {
783 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
784 globals->ob_type->tp_name);
785 return NULL;
786 }
787 if (!PyMapping_Check(locals)) {
788 PyErr_Format(PyExc_TypeError,
789 "arg 3 must be a mapping or None, not %.100s",
790 locals->ob_type->tp_name);
791 return NULL;
792 }
793 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
794 if (PyDict_SetItemString(globals, "__builtins__",
795 PyEval_GetBuiltins()) != 0)
796 return NULL;
797 }
798
799 if (PyCode_Check(prog)) {
800 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
801 PyErr_SetString(PyExc_TypeError,
802 "code object passed to exec() may not "
803 "contain free variables");
804 return NULL;
805 }
806 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
807 }
808 else {
809 char *str;
810 PyCompilerFlags cf;
811 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
812 str = source_as_string(prog, "exec",
813 "string, bytes or code", &cf);
814 if (str == NULL)
815 return NULL;
816 if (PyEval_MergeCompilerFlags(&cf))
817 v = PyRun_StringFlags(str, Py_file_input, globals,
818 locals, &cf);
819 else
820 v = PyRun_String(str, Py_file_input, globals, locals);
821 }
822 if (v == NULL)
823 return NULL;
824 Py_DECREF(v);
825 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000826}
827
828PyDoc_STRVAR(exec_doc,
829"exec(object[, globals[, locals]])\n\
830\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000831Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000832object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000833The globals and locals are dictionaries, defaulting to the current\n\
834globals and locals. If only globals is given, locals defaults to it.");
835
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000836
Guido van Rossum79f25d91997-04-29 20:08:16 +0000837static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000838builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 PyObject *v, *result, *dflt = NULL;
841 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
844 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 if (!PyUnicode_Check(name)) {
847 PyErr_SetString(PyExc_TypeError,
848 "getattr(): attribute name must be string");
849 return NULL;
850 }
851 result = PyObject_GetAttr(v, name);
852 if (result == NULL && dflt != NULL &&
853 PyErr_ExceptionMatches(PyExc_AttributeError))
854 {
855 PyErr_Clear();
856 Py_INCREF(dflt);
857 result = dflt;
858 }
859 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000860}
861
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000862PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000863"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000864\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000865Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
866When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000867exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000868
869
Guido van Rossum79f25d91997-04-29 20:08:16 +0000870static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000871builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 d = PyEval_GetGlobals();
876 Py_XINCREF(d);
877 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000878}
879
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000880PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000881"globals() -> dictionary\n\
882\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000883Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000884
885
Guido van Rossum79f25d91997-04-29 20:08:16 +0000886static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000887builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 PyObject *v;
890 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
893 return NULL;
894 if (!PyUnicode_Check(name)) {
895 PyErr_SetString(PyExc_TypeError,
896 "hasattr(): attribute name must be string");
897 return NULL;
898 }
899 v = PyObject_GetAttr(v, name);
900 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000901 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000903 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000905 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 }
907 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000908 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000909}
910
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000911PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000912"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000913\n\
914Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000915(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000916
917
Guido van Rossum79f25d91997-04-29 20:08:16 +0000918static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000919builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000922}
923
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000924PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000925"id(object) -> integer\n\
926\n\
927Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000928simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000929
930
Raymond Hettingera6c60372008-03-13 01:26:19 +0000931/* map object ************************************************************/
932
933typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 PyObject_HEAD
935 PyObject *iters;
936 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000937} mapobject;
938
Guido van Rossum79f25d91997-04-29 20:08:16 +0000939static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000940map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 PyObject *it, *iters, *func;
943 mapobject *lz;
944 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
947 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 numargs = PyTuple_Size(args);
950 if (numargs < 2) {
951 PyErr_SetString(PyExc_TypeError,
952 "map() must have at least two arguments.");
953 return NULL;
954 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 iters = PyTuple_New(numargs-1);
957 if (iters == NULL)
958 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 for (i=1 ; i<numargs ; i++) {
961 /* Get iterator. */
962 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
963 if (it == NULL) {
964 Py_DECREF(iters);
965 return NULL;
966 }
967 PyTuple_SET_ITEM(iters, i-1, it);
968 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 /* create mapobject structure */
971 lz = (mapobject *)type->tp_alloc(type, 0);
972 if (lz == NULL) {
973 Py_DECREF(iters);
974 return NULL;
975 }
976 lz->iters = iters;
977 func = PyTuple_GET_ITEM(args, 0);
978 Py_INCREF(func);
979 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000982}
983
984static void
985map_dealloc(mapobject *lz)
986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 PyObject_GC_UnTrack(lz);
988 Py_XDECREF(lz->iters);
989 Py_XDECREF(lz->func);
990 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +0000991}
992
993static int
994map_traverse(mapobject *lz, visitproc visit, void *arg)
995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 Py_VISIT(lz->iters);
997 Py_VISIT(lz->func);
998 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000999}
1000
1001static PyObject *
1002map_next(mapobject *lz)
1003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 PyObject *val;
1005 PyObject *argtuple;
1006 PyObject *result;
1007 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 numargs = PyTuple_Size(lz->iters);
1010 argtuple = PyTuple_New(numargs);
1011 if (argtuple == NULL)
1012 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 for (i=0 ; i<numargs ; i++) {
1015 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1016 if (val == NULL) {
1017 Py_DECREF(argtuple);
1018 return NULL;
1019 }
1020 PyTuple_SET_ITEM(argtuple, i, val);
1021 }
1022 result = PyObject_Call(lz->func, argtuple, NULL);
1023 Py_DECREF(argtuple);
1024 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001025}
1026
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001027PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001028"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001029\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001030Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001032
Raymond Hettingera6c60372008-03-13 01:26:19 +00001033PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1035 "map", /* tp_name */
1036 sizeof(mapobject), /* tp_basicsize */
1037 0, /* tp_itemsize */
1038 /* methods */
1039 (destructor)map_dealloc, /* tp_dealloc */
1040 0, /* tp_print */
1041 0, /* tp_getattr */
1042 0, /* tp_setattr */
1043 0, /* tp_reserved */
1044 0, /* tp_repr */
1045 0, /* tp_as_number */
1046 0, /* tp_as_sequence */
1047 0, /* tp_as_mapping */
1048 0, /* tp_hash */
1049 0, /* tp_call */
1050 0, /* tp_str */
1051 PyObject_GenericGetAttr, /* tp_getattro */
1052 0, /* tp_setattro */
1053 0, /* tp_as_buffer */
1054 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1055 Py_TPFLAGS_BASETYPE, /* tp_flags */
1056 map_doc, /* tp_doc */
1057 (traverseproc)map_traverse, /* tp_traverse */
1058 0, /* tp_clear */
1059 0, /* tp_richcompare */
1060 0, /* tp_weaklistoffset */
1061 PyObject_SelfIter, /* tp_iter */
1062 (iternextfunc)map_next, /* tp_iternext */
1063 0, /* tp_methods */
1064 0, /* tp_members */
1065 0, /* tp_getset */
1066 0, /* tp_base */
1067 0, /* tp_dict */
1068 0, /* tp_descr_get */
1069 0, /* tp_descr_set */
1070 0, /* tp_dictoffset */
1071 0, /* tp_init */
1072 PyType_GenericAlloc, /* tp_alloc */
1073 map_new, /* tp_new */
1074 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001075};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001076
Guido van Rossum79f25d91997-04-29 20:08:16 +00001077static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001078builtin_next(PyObject *self, PyObject *args)
1079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 PyObject *it, *res;
1081 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1084 return NULL;
1085 if (!PyIter_Check(it)) {
1086 PyErr_Format(PyExc_TypeError,
1087 "%.200s object is not an iterator",
1088 it->ob_type->tp_name);
1089 return NULL;
1090 }
1091
1092 res = (*it->ob_type->tp_iternext)(it);
1093 if (res != NULL) {
1094 return res;
1095 } else if (def != NULL) {
1096 if (PyErr_Occurred()) {
1097 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1098 return NULL;
1099 PyErr_Clear();
1100 }
1101 Py_INCREF(def);
1102 return def;
1103 } else if (PyErr_Occurred()) {
1104 return NULL;
1105 } else {
1106 PyErr_SetNone(PyExc_StopIteration);
1107 return NULL;
1108 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001109}
1110
1111PyDoc_STRVAR(next_doc,
1112"next(iterator[, default])\n\
1113\n\
1114Return the next item from the iterator. If default is given and the iterator\n\
1115is exhausted, it is returned instead of raising StopIteration.");
1116
1117
1118static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001119builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 PyObject *v;
1122 PyObject *name;
1123 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1126 return NULL;
1127 if (PyObject_SetAttr(v, name, value) != 0)
1128 return NULL;
1129 Py_INCREF(Py_None);
1130 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001131}
1132
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001133PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001134"setattr(object, name, value)\n\
1135\n\
1136Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001137``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001138
1139
Guido van Rossum79f25d91997-04-29 20:08:16 +00001140static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001141builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 PyObject *v;
1144 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1147 return NULL;
1148 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1149 return NULL;
1150 Py_INCREF(Py_None);
1151 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001152}
1153
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001154PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001155"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001156\n\
1157Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001158``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001159
1160
Guido van Rossum79f25d91997-04-29 20:08:16 +00001161static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001162builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001163{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001164 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 x = PyObject_Hash(v);
1167 if (x == -1)
1168 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001169 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001170}
1171
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001172PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001173"hash(object) -> integer\n\
1174\n\
1175Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001176the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001177
1178
Guido van Rossum79f25d91997-04-29 20:08:16 +00001179static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001180builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001183}
1184
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001185PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001186"hex(number) -> string\n\
1187\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001188Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001189
1190
Guido van Rossum79f25d91997-04-29 20:08:16 +00001191static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001192builtin_iter(PyObject *self, PyObject *args)
1193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1197 return NULL;
1198 if (w == NULL)
1199 return PyObject_GetIter(v);
1200 if (!PyCallable_Check(v)) {
1201 PyErr_SetString(PyExc_TypeError,
1202 "iter(v, w): v must be callable");
1203 return NULL;
1204 }
1205 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001206}
1207
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001208PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001209"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001210iter(callable, sentinel) -> iterator\n\
1211\n\
1212Get an iterator from an object. In the first form, the argument must\n\
1213supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001214In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001215
1216
1217static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001218builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 res = PyObject_Size(v);
1223 if (res < 0 && PyErr_Occurred())
1224 return NULL;
1225 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001226}
1227
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001228PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001229"len(object) -> integer\n\
1230\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001231Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001232
1233
Guido van Rossum79f25d91997-04-29 20:08:16 +00001234static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001235builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 d = PyEval_GetLocals();
1240 Py_XINCREF(d);
1241 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001242}
1243
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001244PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001245"locals() -> dictionary\n\
1246\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001247Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001248
1249
Guido van Rossum79f25d91997-04-29 20:08:16 +00001250static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001251min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1254 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 if (PyTuple_Size(args) > 1)
1257 v = args;
1258 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1259 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1262 keyfunc = PyDict_GetItemString(kwds, "key");
1263 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1264 PyErr_Format(PyExc_TypeError,
1265 "%s() got an unexpected keyword argument", name);
1266 return NULL;
1267 }
1268 Py_INCREF(keyfunc);
1269 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 it = PyObject_GetIter(v);
1272 if (it == NULL) {
1273 Py_XDECREF(keyfunc);
1274 return NULL;
1275 }
Tim Petersc3074532001-05-03 07:00:32 +00001276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 maxitem = NULL; /* the result */
1278 maxval = NULL; /* the value associated with the result */
1279 while (( item = PyIter_Next(it) )) {
1280 /* get the value from the key function */
1281 if (keyfunc != NULL) {
1282 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1283 if (val == NULL)
1284 goto Fail_it_item;
1285 }
1286 /* no key function; the value is the item */
1287 else {
1288 val = item;
1289 Py_INCREF(val);
1290 }
Tim Petersc3074532001-05-03 07:00:32 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 /* maximum value and item are unset; set them */
1293 if (maxval == NULL) {
1294 maxitem = item;
1295 maxval = val;
1296 }
1297 /* maximum value and item are set; update them as necessary */
1298 else {
1299 int cmp = PyObject_RichCompareBool(val, maxval, op);
1300 if (cmp < 0)
1301 goto Fail_it_item_and_val;
1302 else if (cmp > 0) {
1303 Py_DECREF(maxval);
1304 Py_DECREF(maxitem);
1305 maxval = val;
1306 maxitem = item;
1307 }
1308 else {
1309 Py_DECREF(item);
1310 Py_DECREF(val);
1311 }
1312 }
1313 }
1314 if (PyErr_Occurred())
1315 goto Fail_it;
1316 if (maxval == NULL) {
1317 PyErr_Format(PyExc_ValueError,
1318 "%s() arg is an empty sequence", name);
1319 assert(maxitem == NULL);
1320 }
1321 else
1322 Py_DECREF(maxval);
1323 Py_DECREF(it);
1324 Py_XDECREF(keyfunc);
1325 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001326
1327Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001329Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001331Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 Py_XDECREF(maxval);
1333 Py_XDECREF(maxitem);
1334 Py_DECREF(it);
1335 Py_XDECREF(keyfunc);
1336 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001337}
1338
Guido van Rossum79f25d91997-04-29 20:08:16 +00001339static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001340builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001343}
1344
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001345PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001346"min(iterable[, key=func]) -> value\n\
1347min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001348\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001349With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001350With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001351
1352
Guido van Rossum79f25d91997-04-29 20:08:16 +00001353static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001354builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001357}
1358
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001359PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001360"max(iterable[, key=func]) -> value\n\
1361max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001362\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001363With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001364With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001365
1366
Guido van Rossum79f25d91997-04-29 20:08:16 +00001367static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001368builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001371}
1372
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001373PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001374"oct(number) -> string\n\
1375\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001376Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001377
1378
Guido van Rossum79f25d91997-04-29 20:08:16 +00001379static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001380builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 long ord;
1383 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 if (PyBytes_Check(obj)) {
1386 size = PyBytes_GET_SIZE(obj);
1387 if (size == 1) {
1388 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1389 return PyLong_FromLong(ord);
1390 }
1391 }
1392 else if (PyUnicode_Check(obj)) {
1393 size = PyUnicode_GET_SIZE(obj);
1394 if (size == 1) {
1395 ord = (long)*PyUnicode_AS_UNICODE(obj);
1396 return PyLong_FromLong(ord);
1397 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001398#ifndef Py_UNICODE_WIDE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 if (size == 2) {
1400 /* Decode a valid surrogate pair */
1401 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1402 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1403 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1404 0xDC00 <= c1 && c1 <= 0xDFFF) {
1405 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1406 0x00010000);
1407 return PyLong_FromLong(ord);
1408 }
1409 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001410#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 }
1412 else if (PyByteArray_Check(obj)) {
1413 /* XXX Hopefully this is temporary */
1414 size = PyByteArray_GET_SIZE(obj);
1415 if (size == 1) {
1416 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1417 return PyLong_FromLong(ord);
1418 }
1419 }
1420 else {
1421 PyErr_Format(PyExc_TypeError,
1422 "ord() expected string of length 1, but " \
1423 "%.200s found", obj->ob_type->tp_name);
1424 return NULL;
1425 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 PyErr_Format(PyExc_TypeError,
1428 "ord() expected a character, "
1429 "but string of length %zd found",
1430 size);
1431 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001432}
1433
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001434PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001435"ord(c) -> integer\n\
1436\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001437Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001438)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001439#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001440PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001441"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001442)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001443#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001444;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001445
1446
Guido van Rossum79f25d91997-04-29 20:08:16 +00001447static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001448builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1453 return NULL;
1454 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001455}
1456
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001457PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001458"pow(x, y[, z]) -> number\n\
1459\n\
1460With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001461equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001462
1463
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001464
Guido van Rossum34343512006-11-30 22:13:52 +00001465static PyObject *
1466builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 static char *kwlist[] = {"sep", "end", "file", 0};
1469 static PyObject *dummy_args;
1470 PyObject *sep = NULL, *end = NULL, *file = NULL;
1471 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 if (dummy_args == NULL) {
1474 if (!(dummy_args = PyTuple_New(0)))
1475 return NULL;
1476 }
1477 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1478 kwlist, &sep, &end, &file))
1479 return NULL;
1480 if (file == NULL || file == Py_None) {
1481 file = PySys_GetObject("stdout");
1482 /* sys.stdout may be None when FILE* stdout isn't connected */
1483 if (file == Py_None)
1484 Py_RETURN_NONE;
1485 }
Guido van Rossum34343512006-11-30 22:13:52 +00001486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 if (sep == Py_None) {
1488 sep = NULL;
1489 }
1490 else if (sep && !PyUnicode_Check(sep)) {
1491 PyErr_Format(PyExc_TypeError,
1492 "sep must be None or a string, not %.200s",
1493 sep->ob_type->tp_name);
1494 return NULL;
1495 }
1496 if (end == Py_None) {
1497 end = NULL;
1498 }
1499 else if (end && !PyUnicode_Check(end)) {
1500 PyErr_Format(PyExc_TypeError,
1501 "end must be None or a string, not %.200s",
1502 end->ob_type->tp_name);
1503 return NULL;
1504 }
Guido van Rossum34343512006-11-30 22:13:52 +00001505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 for (i = 0; i < PyTuple_Size(args); i++) {
1507 if (i > 0) {
1508 if (sep == NULL)
1509 err = PyFile_WriteString(" ", file);
1510 else
1511 err = PyFile_WriteObject(sep, file,
1512 Py_PRINT_RAW);
1513 if (err)
1514 return NULL;
1515 }
1516 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1517 Py_PRINT_RAW);
1518 if (err)
1519 return NULL;
1520 }
Guido van Rossum34343512006-11-30 22:13:52 +00001521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 if (end == NULL)
1523 err = PyFile_WriteString("\n", file);
1524 else
1525 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1526 if (err)
1527 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001530}
1531
1532PyDoc_STRVAR(print_doc,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001533"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001534\n\
1535Prints the values to a stream, or to sys.stdout by default.\n\
1536Optional keyword arguments:\n\
1537file: a file-like object (stream); defaults to the current sys.stdout.\n\
1538sep: string inserted between values, default a space.\n\
1539end: string appended after the last value, default a newline.");
1540
1541
Guido van Rossuma88a0332007-02-26 16:59:55 +00001542static PyObject *
1543builtin_input(PyObject *self, PyObject *args)
1544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 PyObject *promptarg = NULL;
1546 PyObject *fin = PySys_GetObject("stdin");
1547 PyObject *fout = PySys_GetObject("stdout");
1548 PyObject *ferr = PySys_GetObject("stderr");
1549 PyObject *tmp;
1550 long fd;
1551 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 /* Parse arguments */
1554 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1555 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 /* Check that stdin/out/err are intact */
1558 if (fin == NULL || fin == Py_None) {
1559 PyErr_SetString(PyExc_RuntimeError,
1560 "input(): lost sys.stdin");
1561 return NULL;
1562 }
1563 if (fout == NULL || fout == Py_None) {
1564 PyErr_SetString(PyExc_RuntimeError,
1565 "input(): lost sys.stdout");
1566 return NULL;
1567 }
1568 if (ferr == NULL || ferr == Py_None) {
1569 PyErr_SetString(PyExc_RuntimeError,
1570 "input(): lost sys.stderr");
1571 return NULL;
1572 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 /* First of all, flush stderr */
1575 tmp = PyObject_CallMethod(ferr, "flush", "");
1576 if (tmp == NULL)
1577 PyErr_Clear();
1578 else
1579 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 /* We should only use (GNU) readline if Python's sys.stdin and
1582 sys.stdout are the same as C's stdin and stdout, because we
1583 need to pass it those. */
1584 tmp = PyObject_CallMethod(fin, "fileno", "");
1585 if (tmp == NULL) {
1586 PyErr_Clear();
1587 tty = 0;
1588 }
1589 else {
1590 fd = PyLong_AsLong(tmp);
1591 Py_DECREF(tmp);
1592 if (fd < 0 && PyErr_Occurred())
1593 return NULL;
1594 tty = fd == fileno(stdin) && isatty(fd);
1595 }
1596 if (tty) {
1597 tmp = PyObject_CallMethod(fout, "fileno", "");
1598 if (tmp == NULL)
1599 PyErr_Clear();
1600 else {
1601 fd = PyLong_AsLong(tmp);
1602 Py_DECREF(tmp);
1603 if (fd < 0 && PyErr_Occurred())
1604 return NULL;
1605 tty = fd == fileno(stdout) && isatty(fd);
1606 }
1607 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 /* If we're interactive, use (GNU) readline */
1610 if (tty) {
1611 PyObject *po;
1612 char *prompt;
1613 char *s;
1614 PyObject *stdin_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001615 char *stdin_encoding_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 PyObject *result;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1619 if (!stdin_encoding)
1620 /* stdin is a text stream, so it must have an
1621 encoding. */
1622 return NULL;
Victor Stinner306f0102010-05-19 01:06:22 +00001623 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
1624 if (stdin_encoding_str == NULL) {
1625 Py_DECREF(stdin_encoding);
1626 return NULL;
1627 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 tmp = PyObject_CallMethod(fout, "flush", "");
1629 if (tmp == NULL)
1630 PyErr_Clear();
1631 else
1632 Py_DECREF(tmp);
1633 if (promptarg != NULL) {
1634 PyObject *stringpo;
1635 PyObject *stdout_encoding;
Victor Stinner306f0102010-05-19 01:06:22 +00001636 char *stdout_encoding_str;
1637 stdout_encoding = PyObject_GetAttrString(fout, "encoding");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 if (stdout_encoding == NULL) {
1639 Py_DECREF(stdin_encoding);
1640 return NULL;
1641 }
Victor Stinner306f0102010-05-19 01:06:22 +00001642 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
1643 if (stdout_encoding_str == NULL) {
1644 Py_DECREF(stdin_encoding);
1645 Py_DECREF(stdout_encoding);
1646 return NULL;
1647 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 stringpo = PyObject_Str(promptarg);
1649 if (stringpo == NULL) {
1650 Py_DECREF(stdin_encoding);
1651 Py_DECREF(stdout_encoding);
1652 return NULL;
1653 }
1654 po = PyUnicode_AsEncodedString(stringpo,
Victor Stinner306f0102010-05-19 01:06:22 +00001655 stdout_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 Py_DECREF(stdout_encoding);
1657 Py_DECREF(stringpo);
1658 if (po == NULL) {
1659 Py_DECREF(stdin_encoding);
1660 return NULL;
1661 }
1662 prompt = PyBytes_AsString(po);
1663 if (prompt == NULL) {
1664 Py_DECREF(stdin_encoding);
1665 Py_DECREF(po);
1666 return NULL;
1667 }
1668 }
1669 else {
1670 po = NULL;
1671 prompt = "";
1672 }
1673 s = PyOS_Readline(stdin, stdout, prompt);
1674 Py_XDECREF(po);
1675 if (s == NULL) {
1676 if (!PyErr_Occurred())
1677 PyErr_SetNone(PyExc_KeyboardInterrupt);
1678 Py_DECREF(stdin_encoding);
1679 return NULL;
1680 }
1681 if (*s == '\0') {
1682 PyErr_SetNone(PyExc_EOFError);
1683 result = NULL;
1684 }
1685 else { /* strip trailing '\n' */
1686 size_t len = strlen(s);
1687 if (len > PY_SSIZE_T_MAX) {
1688 PyErr_SetString(PyExc_OverflowError,
1689 "input: input too long");
1690 result = NULL;
1691 }
1692 else {
Victor Stinner306f0102010-05-19 01:06:22 +00001693 result = PyUnicode_Decode(s, len-1, stdin_encoding_str, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 }
1695 }
1696 Py_DECREF(stdin_encoding);
1697 PyMem_FREE(s);
1698 return result;
1699 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 /* Fallback if we're not interactive */
1702 if (promptarg != NULL) {
1703 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1704 return NULL;
1705 }
1706 tmp = PyObject_CallMethod(fout, "flush", "");
1707 if (tmp == NULL)
1708 PyErr_Clear();
1709 else
1710 Py_DECREF(tmp);
1711 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001712}
1713
1714PyDoc_STRVAR(input_doc,
1715"input([prompt]) -> string\n\
1716\n\
1717Read a string from standard input. The trailing newline is stripped.\n\
1718If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1719On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1720is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001721
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001722
Guido van Rossum79f25d91997-04-29 20:08:16 +00001723static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001724builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001727}
1728
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001729PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001730"repr(object) -> string\n\
1731\n\
1732Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001733For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001734
1735
Guido van Rossum79f25d91997-04-29 20:08:16 +00001736static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001737builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 static PyObject *round_str = NULL;
1740 PyObject *ndigits = NULL;
1741 static char *kwlist[] = {"number", "ndigits", 0};
1742 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1745 kwlist, &number, &ndigits))
1746 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 if (Py_TYPE(number)->tp_dict == NULL) {
1749 if (PyType_Ready(Py_TYPE(number)) < 0)
1750 return NULL;
1751 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 if (round_str == NULL) {
1754 round_str = PyUnicode_InternFromString("__round__");
1755 if (round_str == NULL)
1756 return NULL;
1757 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 round = _PyType_Lookup(Py_TYPE(number), round_str);
1760 if (round == NULL) {
1761 PyErr_Format(PyExc_TypeError,
1762 "type %.100s doesn't define __round__ method",
1763 Py_TYPE(number)->tp_name);
1764 return NULL;
1765 }
Alex Martelliae211f92007-08-22 23:21:33 +00001766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 if (ndigits == NULL)
1768 return PyObject_CallFunction(round, "O", number);
1769 else
1770 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001771}
1772
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001773PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001774"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001775\n\
1776Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001777This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001778same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001779
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001780
Raymond Hettinger64958a12003-12-17 20:43:33 +00001781static PyObject *
1782builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1785 PyObject *callable;
1786 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1787 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 /* args 1-3 should match listsort in Objects/listobject.c */
1790 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1791 kwlist, &seq, &keyfunc, &reverse))
1792 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 newlist = PySequence_List(seq);
1795 if (newlist == NULL)
1796 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 callable = PyObject_GetAttrString(newlist, "sort");
1799 if (callable == NULL) {
1800 Py_DECREF(newlist);
1801 return NULL;
1802 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 newargs = PyTuple_GetSlice(args, 1, 4);
1805 if (newargs == NULL) {
1806 Py_DECREF(newlist);
1807 Py_DECREF(callable);
1808 return NULL;
1809 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 v = PyObject_Call(callable, newargs, kwds);
1812 Py_DECREF(newargs);
1813 Py_DECREF(callable);
1814 if (v == NULL) {
1815 Py_DECREF(newlist);
1816 return NULL;
1817 }
1818 Py_DECREF(v);
1819 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001820}
1821
1822PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001823"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001824
Guido van Rossum79f25d91997-04-29 20:08:16 +00001825static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001826builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 PyObject *v = NULL;
1829 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1832 return NULL;
1833 if (v == NULL) {
1834 d = PyEval_GetLocals();
1835 if (d == NULL) {
1836 if (!PyErr_Occurred())
1837 PyErr_SetString(PyExc_SystemError,
1838 "vars(): no locals!?");
1839 }
1840 else
1841 Py_INCREF(d);
1842 }
1843 else {
1844 d = PyObject_GetAttrString(v, "__dict__");
1845 if (d == NULL) {
1846 PyErr_SetString(PyExc_TypeError,
1847 "vars() argument must have __dict__ attribute");
1848 return NULL;
1849 }
1850 }
1851 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001852}
1853
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001854PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001855"vars([object]) -> dictionary\n\
1856\n\
1857Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001858With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001859
Alex Martellia70b1912003-04-22 08:12:33 +00001860static PyObject*
1861builtin_sum(PyObject *self, PyObject *args)
1862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 PyObject *seq;
1864 PyObject *result = NULL;
1865 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1868 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 iter = PyObject_GetIter(seq);
1871 if (iter == NULL)
1872 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 if (result == NULL) {
1875 result = PyLong_FromLong(0);
1876 if (result == NULL) {
1877 Py_DECREF(iter);
1878 return NULL;
1879 }
1880 } else {
1881 /* reject string values for 'start' parameter */
1882 if (PyUnicode_Check(result)) {
1883 PyErr_SetString(PyExc_TypeError,
1884 "sum() can't sum strings [use ''.join(seq) instead]");
1885 Py_DECREF(iter);
1886 return NULL;
1887 }
1888 if (PyByteArray_Check(result)) {
1889 PyErr_SetString(PyExc_TypeError,
1890 "sum() can't sum bytes [use b''.join(seq) instead]");
1891 Py_DECREF(iter);
1892 return NULL;
1893 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 Py_INCREF(result);
1896 }
Alex Martellia70b1912003-04-22 08:12:33 +00001897
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001898#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1900 Assumes all inputs are the same type. If the assumption fails, default
1901 to the more general routine.
1902 */
1903 if (PyLong_CheckExact(result)) {
1904 int overflow;
1905 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1906 /* If this already overflowed, don't even enter the loop. */
1907 if (overflow == 0) {
1908 Py_DECREF(result);
1909 result = NULL;
1910 }
1911 while(result == NULL) {
1912 item = PyIter_Next(iter);
1913 if (item == NULL) {
1914 Py_DECREF(iter);
1915 if (PyErr_Occurred())
1916 return NULL;
1917 return PyLong_FromLong(i_result);
1918 }
1919 if (PyLong_CheckExact(item)) {
1920 long b = PyLong_AsLongAndOverflow(item, &overflow);
1921 long x = i_result + b;
1922 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1923 i_result = x;
1924 Py_DECREF(item);
1925 continue;
1926 }
1927 }
1928 /* Either overflowed or is not an int. Restore real objects and process normally */
1929 result = PyLong_FromLong(i_result);
1930 temp = PyNumber_Add(result, item);
1931 Py_DECREF(result);
1932 Py_DECREF(item);
1933 result = temp;
1934 if (result == NULL) {
1935 Py_DECREF(iter);
1936 return NULL;
1937 }
1938 }
1939 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 if (PyFloat_CheckExact(result)) {
1942 double f_result = PyFloat_AS_DOUBLE(result);
1943 Py_DECREF(result);
1944 result = NULL;
1945 while(result == NULL) {
1946 item = PyIter_Next(iter);
1947 if (item == NULL) {
1948 Py_DECREF(iter);
1949 if (PyErr_Occurred())
1950 return NULL;
1951 return PyFloat_FromDouble(f_result);
1952 }
1953 if (PyFloat_CheckExact(item)) {
1954 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1955 f_result += PyFloat_AS_DOUBLE(item);
1956 PyFPE_END_PROTECT(f_result)
1957 Py_DECREF(item);
1958 continue;
1959 }
1960 if (PyLong_CheckExact(item)) {
1961 long value;
1962 int overflow;
1963 value = PyLong_AsLongAndOverflow(item, &overflow);
1964 if (!overflow) {
1965 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1966 f_result += (double)value;
1967 PyFPE_END_PROTECT(f_result)
1968 Py_DECREF(item);
1969 continue;
1970 }
1971 }
1972 result = PyFloat_FromDouble(f_result);
1973 temp = PyNumber_Add(result, item);
1974 Py_DECREF(result);
1975 Py_DECREF(item);
1976 result = temp;
1977 if (result == NULL) {
1978 Py_DECREF(iter);
1979 return NULL;
1980 }
1981 }
1982 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001983#endif
1984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 for(;;) {
1986 item = PyIter_Next(iter);
1987 if (item == NULL) {
1988 /* error, or end-of-sequence */
1989 if (PyErr_Occurred()) {
1990 Py_DECREF(result);
1991 result = NULL;
1992 }
1993 break;
1994 }
1995 /* It's tempting to use PyNumber_InPlaceAdd instead of
1996 PyNumber_Add here, to avoid quadratic running time
1997 when doing 'sum(list_of_lists, [])'. However, this
1998 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00001999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 empty = []
2001 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 would change the value of empty. */
2004 temp = PyNumber_Add(result, item);
2005 Py_DECREF(result);
2006 Py_DECREF(item);
2007 result = temp;
2008 if (result == NULL)
2009 break;
2010 }
2011 Py_DECREF(iter);
2012 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002013}
2014
2015PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002016"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002017\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002018Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2019of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002020empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002021
2022
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002023static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002024builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 PyObject *inst;
2027 PyObject *cls;
2028 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2031 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 retval = PyObject_IsInstance(inst, cls);
2034 if (retval < 0)
2035 return NULL;
2036 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002037}
2038
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002039PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002040"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002041\n\
2042Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002043With a type as second argument, return whether that is the object's type.\n\
2044The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002045isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002046
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002047
2048static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002049builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 PyObject *derived;
2052 PyObject *cls;
2053 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2056 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 retval = PyObject_IsSubclass(derived, cls);
2059 if (retval < 0)
2060 return NULL;
2061 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002062}
2063
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002064PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002065"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002066\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002067Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2068When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2069is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002070
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002071
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002072typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 PyObject_HEAD
2074 Py_ssize_t tuplesize;
2075 PyObject *ittuple; /* tuple of iterators */
2076 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002077} zipobject;
2078
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002079static PyObject *
2080zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 zipobject *lz;
2083 Py_ssize_t i;
2084 PyObject *ittuple; /* tuple of iterators */
2085 PyObject *result;
2086 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2089 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 /* args must be a tuple */
2092 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 /* obtain iterators */
2095 ittuple = PyTuple_New(tuplesize);
2096 if (ittuple == NULL)
2097 return NULL;
2098 for (i=0; i < tuplesize; ++i) {
2099 PyObject *item = PyTuple_GET_ITEM(args, i);
2100 PyObject *it = PyObject_GetIter(item);
2101 if (it == NULL) {
2102 if (PyErr_ExceptionMatches(PyExc_TypeError))
2103 PyErr_Format(PyExc_TypeError,
2104 "zip argument #%zd must support iteration",
2105 i+1);
2106 Py_DECREF(ittuple);
2107 return NULL;
2108 }
2109 PyTuple_SET_ITEM(ittuple, i, it);
2110 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 /* create a result holder */
2113 result = PyTuple_New(tuplesize);
2114 if (result == NULL) {
2115 Py_DECREF(ittuple);
2116 return NULL;
2117 }
2118 for (i=0 ; i < tuplesize ; i++) {
2119 Py_INCREF(Py_None);
2120 PyTuple_SET_ITEM(result, i, Py_None);
2121 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 /* create zipobject structure */
2124 lz = (zipobject *)type->tp_alloc(type, 0);
2125 if (lz == NULL) {
2126 Py_DECREF(ittuple);
2127 Py_DECREF(result);
2128 return NULL;
2129 }
2130 lz->ittuple = ittuple;
2131 lz->tuplesize = tuplesize;
2132 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002135}
2136
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002137static void
2138zip_dealloc(zipobject *lz)
2139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 PyObject_GC_UnTrack(lz);
2141 Py_XDECREF(lz->ittuple);
2142 Py_XDECREF(lz->result);
2143 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002144}
2145
2146static int
2147zip_traverse(zipobject *lz, visitproc visit, void *arg)
2148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 Py_VISIT(lz->ittuple);
2150 Py_VISIT(lz->result);
2151 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002152}
2153
2154static PyObject *
2155zip_next(zipobject *lz)
2156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 Py_ssize_t i;
2158 Py_ssize_t tuplesize = lz->tuplesize;
2159 PyObject *result = lz->result;
2160 PyObject *it;
2161 PyObject *item;
2162 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 if (tuplesize == 0)
2165 return NULL;
2166 if (Py_REFCNT(result) == 1) {
2167 Py_INCREF(result);
2168 for (i=0 ; i < tuplesize ; i++) {
2169 it = PyTuple_GET_ITEM(lz->ittuple, i);
2170 item = (*Py_TYPE(it)->tp_iternext)(it);
2171 if (item == NULL) {
2172 Py_DECREF(result);
2173 return NULL;
2174 }
2175 olditem = PyTuple_GET_ITEM(result, i);
2176 PyTuple_SET_ITEM(result, i, item);
2177 Py_DECREF(olditem);
2178 }
2179 } else {
2180 result = PyTuple_New(tuplesize);
2181 if (result == NULL)
2182 return NULL;
2183 for (i=0 ; i < tuplesize ; i++) {
2184 it = PyTuple_GET_ITEM(lz->ittuple, i);
2185 item = (*Py_TYPE(it)->tp_iternext)(it);
2186 if (item == NULL) {
2187 Py_DECREF(result);
2188 return NULL;
2189 }
2190 PyTuple_SET_ITEM(result, i, item);
2191 }
2192 }
2193 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002194}
Barry Warsawbd599b52000-08-03 15:45:29 +00002195
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002196PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002197"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002198\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002199Return a zip object whose .__next__() method returns a tuple where\n\
2200the i-th element comes from the i-th iterable argument. The .__next__()\n\
2201method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002202is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002203
2204PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2206 "zip", /* tp_name */
2207 sizeof(zipobject), /* tp_basicsize */
2208 0, /* tp_itemsize */
2209 /* methods */
2210 (destructor)zip_dealloc, /* tp_dealloc */
2211 0, /* tp_print */
2212 0, /* tp_getattr */
2213 0, /* tp_setattr */
2214 0, /* tp_reserved */
2215 0, /* tp_repr */
2216 0, /* tp_as_number */
2217 0, /* tp_as_sequence */
2218 0, /* tp_as_mapping */
2219 0, /* tp_hash */
2220 0, /* tp_call */
2221 0, /* tp_str */
2222 PyObject_GenericGetAttr, /* tp_getattro */
2223 0, /* tp_setattro */
2224 0, /* tp_as_buffer */
2225 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2226 Py_TPFLAGS_BASETYPE, /* tp_flags */
2227 zip_doc, /* tp_doc */
2228 (traverseproc)zip_traverse, /* tp_traverse */
2229 0, /* tp_clear */
2230 0, /* tp_richcompare */
2231 0, /* tp_weaklistoffset */
2232 PyObject_SelfIter, /* tp_iter */
2233 (iternextfunc)zip_next, /* tp_iternext */
2234 0, /* tp_methods */
2235 0, /* tp_members */
2236 0, /* tp_getset */
2237 0, /* tp_base */
2238 0, /* tp_dict */
2239 0, /* tp_descr_get */
2240 0, /* tp_descr_set */
2241 0, /* tp_dictoffset */
2242 0, /* tp_init */
2243 PyType_GenericAlloc, /* tp_alloc */
2244 zip_new, /* tp_new */
2245 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002246};
Barry Warsawbd599b52000-08-03 15:45:29 +00002247
2248
Guido van Rossum79f25d91997-04-29 20:08:16 +00002249static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 {"__build_class__", (PyCFunction)builtin___build_class__,
2251 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2252 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2253 {"abs", builtin_abs, METH_O, abs_doc},
2254 {"all", builtin_all, METH_O, all_doc},
2255 {"any", builtin_any, METH_O, any_doc},
2256 {"ascii", builtin_ascii, METH_O, ascii_doc},
2257 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002258 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2260 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2261 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2262 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2263 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2264 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2265 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2266 {"format", builtin_format, METH_VARARGS, format_doc},
2267 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2268 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2269 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2270 {"hash", builtin_hash, METH_O, hash_doc},
2271 {"hex", builtin_hex, METH_O, hex_doc},
2272 {"id", builtin_id, METH_O, id_doc},
2273 {"input", builtin_input, METH_VARARGS, input_doc},
2274 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2275 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2276 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2277 {"len", builtin_len, METH_O, len_doc},
2278 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2279 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2280 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2281 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2282 {"oct", builtin_oct, METH_O, oct_doc},
2283 {"ord", builtin_ord, METH_O, ord_doc},
2284 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2285 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2286 {"repr", builtin_repr, METH_O, repr_doc},
2287 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2288 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2289 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2290 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2291 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2292 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002293};
2294
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002295PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002296"Built-in functions, exceptions, and other objects.\n\
2297\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002298Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002299
Martin v. Löwis1a214512008-06-11 05:26:20 +00002300static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 PyModuleDef_HEAD_INIT,
2302 "builtins",
2303 builtin_doc,
2304 -1, /* multiple "initialization" just copies the module dict. */
2305 builtin_methods,
2306 NULL,
2307 NULL,
2308 NULL,
2309 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002310};
2311
2312
Guido van Rossum25ce5661997-08-02 03:10:38 +00002313PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002314_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 PyObject *mod, *dict, *debug;
2317 mod = PyModule_Create(&builtinsmodule);
2318 if (mod == NULL)
2319 return NULL;
2320 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002321
Tim Peters7571a0f2003-03-23 17:52:28 +00002322#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 /* "builtins" exposes a number of statically allocated objects
2324 * that, before this code was added in 2.3, never showed up in
2325 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2326 * result, programs leaking references to None and False (etc)
2327 * couldn't be diagnosed by examining sys.getobjects(0).
2328 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002329#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2330#else
2331#define ADD_TO_ALL(OBJECT) (void)0
2332#endif
2333
Tim Peters4b7625e2001-09-13 21:37:17 +00002334#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2336 return NULL; \
2337 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 SETBUILTIN("None", Py_None);
2340 SETBUILTIN("Ellipsis", Py_Ellipsis);
2341 SETBUILTIN("NotImplemented", Py_NotImplemented);
2342 SETBUILTIN("False", Py_False);
2343 SETBUILTIN("True", Py_True);
2344 SETBUILTIN("bool", &PyBool_Type);
2345 SETBUILTIN("memoryview", &PyMemoryView_Type);
2346 SETBUILTIN("bytearray", &PyByteArray_Type);
2347 SETBUILTIN("bytes", &PyBytes_Type);
2348 SETBUILTIN("classmethod", &PyClassMethod_Type);
2349 SETBUILTIN("complex", &PyComplex_Type);
2350 SETBUILTIN("dict", &PyDict_Type);
2351 SETBUILTIN("enumerate", &PyEnum_Type);
2352 SETBUILTIN("filter", &PyFilter_Type);
2353 SETBUILTIN("float", &PyFloat_Type);
2354 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2355 SETBUILTIN("property", &PyProperty_Type);
2356 SETBUILTIN("int", &PyLong_Type);
2357 SETBUILTIN("list", &PyList_Type);
2358 SETBUILTIN("map", &PyMap_Type);
2359 SETBUILTIN("object", &PyBaseObject_Type);
2360 SETBUILTIN("range", &PyRange_Type);
2361 SETBUILTIN("reversed", &PyReversed_Type);
2362 SETBUILTIN("set", &PySet_Type);
2363 SETBUILTIN("slice", &PySlice_Type);
2364 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2365 SETBUILTIN("str", &PyUnicode_Type);
2366 SETBUILTIN("super", &PySuper_Type);
2367 SETBUILTIN("tuple", &PyTuple_Type);
2368 SETBUILTIN("type", &PyType_Type);
2369 SETBUILTIN("zip", &PyZip_Type);
2370 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2371 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2372 Py_XDECREF(debug);
2373 return NULL;
2374 }
2375 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002378#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002379#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002380}