This commit was manufactured by cvs2svn to create tag
[python/dscho.git] / Python / bltinmodule.c
blobf5ce74975c10f2119c0ac0063b8e1b1fbf059066
2 /* Built-in functions */
4 #include "Python.h"
6 #include "node.h"
7 #include "compile.h"
8 #include "eval.h"
10 #include <ctype.h>
12 #ifdef HAVE_UNISTD_H
13 #include <unistd.h>
14 #endif
16 #ifdef RISCOS
17 #include "unixstuff.h"
18 #endif
20 /* The default encoding used by the platform file system APIs
21 Can remain NULL for all platforms that don't have such a concept
23 #if defined(MS_WIN32) && defined(HAVE_USABLE_WCHAR_T)
24 const char *Py_FileSystemDefaultEncoding = "mbcs";
25 #else
26 const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
27 #endif
29 /* Forward */
30 static PyObject *filterstring(PyObject *, PyObject *);
31 static PyObject *filtertuple (PyObject *, PyObject *);
33 static PyObject *
34 builtin___import__(PyObject *self, PyObject *args)
36 char *name;
37 PyObject *globals = NULL;
38 PyObject *locals = NULL;
39 PyObject *fromlist = NULL;
41 if (!PyArg_ParseTuple(args, "s|OOO:__import__",
42 &name, &globals, &locals, &fromlist))
43 return NULL;
44 return PyImport_ImportModuleEx(name, globals, locals, fromlist);
47 static char import_doc[] =
48 "__import__(name, globals, locals, fromlist) -> module\n\
49 \n\
50 Import a module. The globals are only used to determine the context;\n\
51 they are not modified. The locals are currently unused. The fromlist\n\
52 should be a list of names to emulate ``from name import ...'', or an\n\
53 empty list to emulate ``import name''.\n\
54 When importing a module from a package, note that __import__('A.B', ...)\n\
55 returns package A when fromlist is empty, but its submodule B when\n\
56 fromlist is not empty.";
59 static PyObject *
60 builtin_abs(PyObject *self, PyObject *v)
62 return PyNumber_Absolute(v);
65 static char abs_doc[] =
66 "abs(number) -> number\n\
67 \n\
68 Return the absolute value of the argument.";
71 static PyObject *
72 builtin_apply(PyObject *self, PyObject *args)
74 PyObject *func, *alist = NULL, *kwdict = NULL;
75 PyObject *t = NULL, *retval = NULL;
77 if (!PyArg_ParseTuple(args, "O|OO:apply", &func, &alist, &kwdict))
78 return NULL;
79 if (alist != NULL) {
80 if (!PyTuple_Check(alist)) {
81 if (!PySequence_Check(alist)) {
82 PyErr_Format(PyExc_TypeError,
83 "apply() arg 2 expect sequence, found %s",
84 alist->ob_type->tp_name);
85 return NULL;
87 t = PySequence_Tuple(alist);
88 if (t == NULL)
89 return NULL;
90 alist = t;
93 if (kwdict != NULL && !PyDict_Check(kwdict)) {
94 PyErr_Format(PyExc_TypeError,
95 "apply() arg 3 expected dictionary, found %s",
96 kwdict->ob_type->tp_name);
97 goto finally;
99 retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
100 finally:
101 Py_XDECREF(t);
102 return retval;
105 static char apply_doc[] =
106 "apply(object[, args[, kwargs]]) -> value\n\
108 Call a callable object with positional arguments taken from the tuple args,\n\
109 and keyword arguments taken from the optional dictionary kwargs.\n\
110 Note that classes are callable, as are instances with a __call__() method.";
113 static PyObject *
114 builtin_buffer(PyObject *self, PyObject *args)
116 PyObject *ob;
117 int offset = 0;
118 int size = Py_END_OF_BUFFER;
120 if ( !PyArg_ParseTuple(args, "O|ii:buffer", &ob, &offset, &size) )
121 return NULL;
122 return PyBuffer_FromObject(ob, offset, size);
125 static char buffer_doc[] =
126 "buffer(object [, offset[, size]]) -> object\n\
128 Create a new buffer object which references the given object.\n\
129 The buffer will reference a slice of the target object from the\n\
130 start of the object (or at the specified offset). The slice will\n\
131 extend to the end of the target object (or with the specified size).";
134 static PyObject *
135 builtin_callable(PyObject *self, PyObject *v)
137 return PyInt_FromLong((long)PyCallable_Check(v));
140 static char callable_doc[] =
141 "callable(object) -> Boolean\n\
143 Return whether the object is callable (i.e., some kind of function).\n\
144 Note that classes are callable, as are instances with a __call__() method.";
147 static PyObject *
148 builtin_filter(PyObject *self, PyObject *args)
150 PyObject *func, *seq, *result, *it;
151 int len; /* guess for result list size */
152 register int j;
154 if (!PyArg_ParseTuple(args, "OO:filter", &func, &seq))
155 return NULL;
157 /* Strings and tuples return a result of the same type. */
158 if (PyString_Check(seq))
159 return filterstring(func, seq);
160 if (PyTuple_Check(seq))
161 return filtertuple(func, seq);
163 /* Get iterator. */
164 it = PyObject_GetIter(seq);
165 if (it == NULL)
166 return NULL;
168 /* Guess a result list size. */
169 len = -1; /* unknown */
170 if (PySequence_Check(seq) &&
171 seq->ob_type->tp_as_sequence->sq_length) {
172 len = PySequence_Size(seq);
173 if (len < 0)
174 PyErr_Clear();
176 if (len < 0)
177 len = 8; /* arbitrary */
179 /* Get a result list. */
180 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
181 /* Eww - can modify the list in-place. */
182 Py_INCREF(seq);
183 result = seq;
185 else {
186 result = PyList_New(len);
187 if (result == NULL)
188 goto Fail_it;
191 /* Build the result list. */
192 j = 0;
193 for (;;) {
194 PyObject *item, *good;
195 int ok;
197 item = PyIter_Next(it);
198 if (item == NULL) {
199 if (PyErr_Occurred())
200 goto Fail_result_it;
201 break;
204 if (func == Py_None) {
205 good = item;
206 Py_INCREF(good);
208 else {
209 PyObject *arg = Py_BuildValue("(O)", item);
210 if (arg == NULL) {
211 Py_DECREF(item);
212 goto Fail_result_it;
214 good = PyEval_CallObject(func, arg);
215 Py_DECREF(arg);
216 if (good == NULL) {
217 Py_DECREF(item);
218 goto Fail_result_it;
221 ok = PyObject_IsTrue(good);
222 Py_DECREF(good);
223 if (ok) {
224 if (j < len)
225 PyList_SET_ITEM(result, j, item);
226 else {
227 int status = PyList_Append(result, item);
228 Py_DECREF(item);
229 if (status < 0)
230 goto Fail_result_it;
232 ++j;
234 else
235 Py_DECREF(item);
239 /* Cut back result list if len is too big. */
240 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
241 goto Fail_result_it;
243 Py_DECREF(it);
244 return result;
246 Fail_result_it:
247 Py_DECREF(result);
248 Fail_it:
249 Py_DECREF(it);
250 return NULL;
253 static char filter_doc[] =
254 "filter(function, sequence) -> list\n\
256 Return a list containing those items of sequence for which function(item)\n\
257 is true. If function is None, return a list of items that are true.";
260 static PyObject *
261 builtin_chr(PyObject *self, PyObject *args)
263 long x;
264 char s[1];
266 if (!PyArg_ParseTuple(args, "l:chr", &x))
267 return NULL;
268 if (x < 0 || x >= 256) {
269 PyErr_SetString(PyExc_ValueError,
270 "chr() arg not in range(256)");
271 return NULL;
273 s[0] = (char)x;
274 return PyString_FromStringAndSize(s, 1);
277 static char chr_doc[] =
278 "chr(i) -> character\n\
280 Return a string of one character with ordinal i; 0 <= i < 256.";
283 #ifdef Py_USING_UNICODE
284 static PyObject *
285 builtin_unichr(PyObject *self, PyObject *args)
287 long x;
288 Py_UNICODE s[2];
290 if (!PyArg_ParseTuple(args, "l:unichr", &x))
291 return NULL;
293 #ifdef Py_UNICODE_WIDE
294 if (x < 0 || x > 0x10ffff) {
295 PyErr_SetString(PyExc_ValueError,
296 "unichr() arg not in range(0x110000) "
297 "(wide Python build)");
298 return NULL;
300 #else
301 if (x < 0 || x > 0xffff) {
302 PyErr_SetString(PyExc_ValueError,
303 "unichr() arg not in range(0x10000) "
304 "(narrow Python build)");
305 return NULL;
307 #endif
309 if (x <= 0xffff) {
310 /* UCS-2 character */
311 s[0] = (Py_UNICODE) x;
312 return PyUnicode_FromUnicode(s, 1);
314 else {
315 #ifndef Py_UNICODE_WIDE
316 /* UCS-4 character. store as two surrogate characters */
317 x -= 0x10000L;
318 s[0] = 0xD800 + (Py_UNICODE) (x >> 10);
319 s[1] = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
320 return PyUnicode_FromUnicode(s, 2);
321 #else
322 s[0] = (Py_UNICODE)x;
323 return PyUnicode_FromUnicode(s, 1);
324 #endif
328 static char unichr_doc[] =
329 "unichr(i) -> Unicode character\n\
331 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.";
332 #endif
335 static PyObject *
336 builtin_cmp(PyObject *self, PyObject *args)
338 PyObject *a, *b;
339 int c;
341 if (!PyArg_ParseTuple(args, "OO:cmp", &a, &b))
342 return NULL;
343 if (PyObject_Cmp(a, b, &c) < 0)
344 return NULL;
345 return PyInt_FromLong((long)c);
348 static char cmp_doc[] =
349 "cmp(x, y) -> integer\n\
351 Return negative if x<y, zero if x==y, positive if x>y.";
354 static PyObject *
355 builtin_coerce(PyObject *self, PyObject *args)
357 PyObject *v, *w;
358 PyObject *res;
360 if (!PyArg_ParseTuple(args, "OO:coerce", &v, &w))
361 return NULL;
362 if (PyNumber_Coerce(&v, &w) < 0)
363 return NULL;
364 res = Py_BuildValue("(OO)", v, w);
365 Py_DECREF(v);
366 Py_DECREF(w);
367 return res;
370 static char coerce_doc[] =
371 "coerce(x, y) -> None or (x1, y1)\n\
373 When x and y can be coerced to values of the same type, return a tuple\n\
374 containing the coerced values. When they can't be coerced, return None.";
377 static PyObject *
378 builtin_compile(PyObject *self, PyObject *args)
380 char *str;
381 char *filename;
382 char *startstr;
383 int start;
384 int dont_inherit = 0;
385 int supplied_flags = 0;
386 PyCompilerFlags cf;
388 if (!PyArg_ParseTuple(args, "sss|ii:compile", &str, &filename,
389 &startstr, &supplied_flags, &dont_inherit))
390 return NULL;
392 if (strcmp(startstr, "exec") == 0)
393 start = Py_file_input;
394 else if (strcmp(startstr, "eval") == 0)
395 start = Py_eval_input;
396 else if (strcmp(startstr, "single") == 0)
397 start = Py_single_input;
398 else {
399 PyErr_SetString(PyExc_ValueError,
400 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
401 return NULL;
404 if (supplied_flags & ~(PyCF_MASK | PyCF_MASK_OBSOLETE)) {
405 PyErr_SetString(PyExc_ValueError,
406 "compile(): unrecognised flags");
407 return NULL;
409 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
411 cf.cf_flags = supplied_flags;
412 if (!dont_inherit) {
413 PyEval_MergeCompilerFlags(&cf);
415 return Py_CompileStringFlags(str, filename, start, &cf);
418 static char compile_doc[] =
419 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
421 Compile the source string (a Python module, statement or expression)\n\
422 into a code object that can be executed by the exec statement or eval().\n\
423 The filename will be used for run-time error messages.\n\
424 The mode must be 'exec' to compile a module, 'single' to compile a\n\
425 single (interactive) statement, or 'eval' to compile an expression.\n\
426 The flags argument, if present, controls which future statements influence\n\
427 the compilation of the code.\n\
428 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
429 the effects of any future statements in effect in the code calling\n\
430 compile; if absent or zero these statements do influence the compilation,\n\
431 in addition to any features explicitly specified.";
433 static PyObject *
434 builtin_dir(PyObject *self, PyObject *args)
436 PyObject *arg = NULL;
438 if (!PyArg_ParseTuple(args, "|O:dir", &arg))
439 return NULL;
440 return PyObject_Dir(arg);
443 static char dir_doc[] =
444 "dir([object]) -> list of strings\n"
445 "\n"
446 "Return an alphabetized list of names comprising (some of) the attributes\n"
447 "of the given object, and of attributes reachable from it:\n"
448 "\n"
449 "No argument: the names in the current scope.\n"
450 "Module object: the module attributes.\n"
451 "Type or class object: its attributes, and recursively the attributes of\n"
452 " its bases.\n"
453 "Otherwise: its attributes, its class's attributes, and recursively the\n"
454 " attributes of its class's base classes.";
456 static PyObject *
457 builtin_divmod(PyObject *self, PyObject *args)
459 PyObject *v, *w;
461 if (!PyArg_ParseTuple(args, "OO:divmod", &v, &w))
462 return NULL;
463 return PyNumber_Divmod(v, w);
466 static char divmod_doc[] =
467 "divmod(x, y) -> (div, mod)\n\
469 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.";
472 static PyObject *
473 builtin_eval(PyObject *self, PyObject *args)
475 PyObject *cmd;
476 PyObject *globals = Py_None, *locals = Py_None;
477 char *str;
478 PyCompilerFlags cf;
480 if (!PyArg_ParseTuple(args, "O|O!O!:eval",
481 &cmd,
482 &PyDict_Type, &globals,
483 &PyDict_Type, &locals))
484 return NULL;
485 if (globals == Py_None) {
486 globals = PyEval_GetGlobals();
487 if (locals == Py_None)
488 locals = PyEval_GetLocals();
490 else if (locals == Py_None)
491 locals = globals;
493 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
494 if (PyDict_SetItemString(globals, "__builtins__",
495 PyEval_GetBuiltins()) != 0)
496 return NULL;
499 if (PyCode_Check(cmd)) {
500 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
501 PyErr_SetString(PyExc_TypeError,
502 "code object passed to eval() may not contain free variables");
503 return NULL;
505 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
508 if (!PyString_Check(cmd) &&
509 !PyUnicode_Check(cmd)) {
510 PyErr_SetString(PyExc_TypeError,
511 "eval() arg 1 must be a string or code object");
512 return NULL;
514 if (PyString_AsStringAndSize(cmd, &str, NULL))
515 return NULL;
516 while (*str == ' ' || *str == '\t')
517 str++;
519 cf.cf_flags = 0;
520 (void)PyEval_MergeCompilerFlags(&cf);
521 return PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
524 static char eval_doc[] =
525 "eval(source[, globals[, locals]]) -> value\n\
527 Evaluate the source in the context of globals and locals.\n\
528 The source may be a string representing a Python expression\n\
529 or a code object as returned by compile().\n\
530 The globals and locals are dictionaries, defaulting to the current\n\
531 globals and locals. If only globals is given, locals defaults to it.";
534 static PyObject *
535 builtin_execfile(PyObject *self, PyObject *args)
537 char *filename;
538 PyObject *globals = Py_None, *locals = Py_None;
539 PyObject *res;
540 FILE* fp = NULL;
541 PyCompilerFlags cf;
542 int exists;
543 #ifndef RISCOS
544 struct stat s;
545 #endif
547 if (!PyArg_ParseTuple(args, "s|O!O!:execfile",
548 &filename,
549 &PyDict_Type, &globals,
550 &PyDict_Type, &locals))
551 return NULL;
552 if (globals == Py_None) {
553 globals = PyEval_GetGlobals();
554 if (locals == Py_None)
555 locals = PyEval_GetLocals();
557 else if (locals == Py_None)
558 locals = globals;
559 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
560 if (PyDict_SetItemString(globals, "__builtins__",
561 PyEval_GetBuiltins()) != 0)
562 return NULL;
565 exists = 0;
566 /* Test for existence or directory. */
567 #ifndef RISCOS
568 if (!stat(filename, &s)) {
569 if (S_ISDIR(s.st_mode))
570 #if defined(PYOS_OS2) && defined(PYCC_VACPP)
571 errno = EOS2ERR;
572 #else
573 errno = EISDIR;
574 #endif
575 else
576 exists = 1;
578 #else
579 if (object_exists(filename)) {
580 if (isdir(filename))
581 errno = EISDIR;
582 else
583 exists = 1;
585 #endif /* RISCOS */
587 if (exists) {
588 Py_BEGIN_ALLOW_THREADS
589 fp = fopen(filename, "r");
590 Py_END_ALLOW_THREADS
592 if (fp == NULL) {
593 exists = 0;
597 if (!exists) {
598 PyErr_SetFromErrno(PyExc_IOError);
599 return NULL;
601 cf.cf_flags = 0;
602 if (PyEval_MergeCompilerFlags(&cf))
603 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
604 locals, 1, &cf);
605 else
606 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
607 locals, 1);
608 return res;
611 static char execfile_doc[] =
612 "execfile(filename[, globals[, locals]])\n\
614 Read and execute a Python script from a file.\n\
615 The globals and locals are dictionaries, defaulting to the current\n\
616 globals and locals. If only globals is given, locals defaults to it.";
619 static PyObject *
620 builtin_getattr(PyObject *self, PyObject *args)
622 PyObject *v, *result, *dflt = NULL;
623 PyObject *name;
625 if (!PyArg_ParseTuple(args, "OO|O:getattr", &v, &name, &dflt))
626 return NULL;
627 #ifdef Py_USING_UNICODE
628 if (PyUnicode_Check(name)) {
629 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
630 if (name == NULL)
631 return NULL;
633 #endif
635 if (!PyString_Check(name)) {
636 PyErr_SetString(PyExc_TypeError,
637 "attribute name must be string");
638 return NULL;
640 result = PyObject_GetAttr(v, name);
641 if (result == NULL && dflt != NULL &&
642 PyErr_ExceptionMatches(PyExc_AttributeError))
644 PyErr_Clear();
645 Py_INCREF(dflt);
646 result = dflt;
648 return result;
651 static char getattr_doc[] =
652 "getattr(object, name[, default]) -> value\n\
654 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
655 When a default argument is given, it is returned when the attribute doesn't\n\
656 exist; without it, an exception is raised in that case.";
659 static PyObject *
660 builtin_globals(PyObject *self)
662 PyObject *d;
664 d = PyEval_GetGlobals();
665 Py_INCREF(d);
666 return d;
669 static char globals_doc[] =
670 "globals() -> dictionary\n\
672 Return the dictionary containing the current scope's global variables.";
675 static PyObject *
676 builtin_hasattr(PyObject *self, PyObject *args)
678 PyObject *v;
679 PyObject *name;
681 if (!PyArg_ParseTuple(args, "OO:hasattr", &v, &name))
682 return NULL;
683 #ifdef Py_USING_UNICODE
684 if (PyUnicode_Check(name)) {
685 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
686 if (name == NULL)
687 return NULL;
689 #endif
691 if (!PyString_Check(name)) {
692 PyErr_SetString(PyExc_TypeError,
693 "attribute name must be string");
694 return NULL;
696 v = PyObject_GetAttr(v, name);
697 if (v == NULL) {
698 PyErr_Clear();
699 Py_INCREF(Py_False);
700 return Py_False;
702 Py_DECREF(v);
703 Py_INCREF(Py_True);
704 return Py_True;
707 static char hasattr_doc[] =
708 "hasattr(object, name) -> Boolean\n\
710 Return whether the object has an attribute with the given name.\n\
711 (This is done by calling getattr(object, name) and catching exceptions.)";
714 static PyObject *
715 builtin_id(PyObject *self, PyObject *v)
717 return PyLong_FromVoidPtr(v);
720 static char id_doc[] =
721 "id(object) -> integer\n\
723 Return the identity of an object. This is guaranteed to be unique among\n\
724 simultaneously existing objects. (Hint: it's the object's memory address.)";
727 static PyObject *
728 builtin_map(PyObject *self, PyObject *args)
730 typedef struct {
731 PyObject *it; /* the iterator object */
732 int saw_StopIteration; /* bool: did the iterator end? */
733 } sequence;
735 PyObject *func, *result;
736 sequence *seqs = NULL, *sqp;
737 int n, len;
738 register int i, j;
740 n = PyTuple_Size(args);
741 if (n < 2) {
742 PyErr_SetString(PyExc_TypeError,
743 "map() requires at least two args");
744 return NULL;
747 func = PyTuple_GetItem(args, 0);
748 n--;
750 if (func == Py_None && n == 1) {
751 /* map(None, S) is the same as list(S). */
752 return PySequence_List(PyTuple_GetItem(args, 1));
755 /* Get space for sequence descriptors. Must NULL out the iterator
756 * pointers so that jumping to Fail_2 later doesn't see trash.
758 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
759 PyErr_NoMemory();
760 return NULL;
762 for (i = 0; i < n; ++i) {
763 seqs[i].it = (PyObject*)NULL;
764 seqs[i].saw_StopIteration = 0;
767 /* Do a first pass to obtain iterators for the arguments, and set len
768 * to the largest of their lengths.
770 len = 0;
771 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
772 PyObject *curseq;
773 int curlen;
775 /* Get iterator. */
776 curseq = PyTuple_GetItem(args, i+1);
777 sqp->it = PyObject_GetIter(curseq);
778 if (sqp->it == NULL) {
779 static char errmsg[] =
780 "argument %d to map() must support iteration";
781 char errbuf[sizeof(errmsg) + 25];
782 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
783 PyErr_SetString(PyExc_TypeError, errbuf);
784 goto Fail_2;
787 /* Update len. */
788 curlen = -1; /* unknown */
789 if (PySequence_Check(curseq) &&
790 curseq->ob_type->tp_as_sequence->sq_length) {
791 curlen = PySequence_Size(curseq);
792 if (curlen < 0)
793 PyErr_Clear();
795 if (curlen < 0)
796 curlen = 8; /* arbitrary */
797 if (curlen > len)
798 len = curlen;
801 /* Get space for the result list. */
802 if ((result = (PyObject *) PyList_New(len)) == NULL)
803 goto Fail_2;
805 /* Iterate over the sequences until all have stopped. */
806 for (i = 0; ; ++i) {
807 PyObject *alist, *item=NULL, *value;
808 int numactive = 0;
810 if (func == Py_None && n == 1)
811 alist = NULL;
812 else if ((alist = PyTuple_New(n)) == NULL)
813 goto Fail_1;
815 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
816 if (sqp->saw_StopIteration) {
817 Py_INCREF(Py_None);
818 item = Py_None;
820 else {
821 item = PyIter_Next(sqp->it);
822 if (item)
823 ++numactive;
824 else {
825 if (PyErr_Occurred()) {
826 Py_XDECREF(alist);
827 goto Fail_1;
829 Py_INCREF(Py_None);
830 item = Py_None;
831 sqp->saw_StopIteration = 1;
834 if (alist)
835 PyTuple_SET_ITEM(alist, j, item);
836 else
837 break;
840 if (!alist)
841 alist = item;
843 if (numactive == 0) {
844 Py_DECREF(alist);
845 break;
848 if (func == Py_None)
849 value = alist;
850 else {
851 value = PyEval_CallObject(func, alist);
852 Py_DECREF(alist);
853 if (value == NULL)
854 goto Fail_1;
856 if (i >= len) {
857 int status = PyList_Append(result, value);
858 Py_DECREF(value);
859 if (status < 0)
860 goto Fail_1;
862 else if (PyList_SetItem(result, i, value) < 0)
863 goto Fail_1;
866 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
867 goto Fail_1;
869 goto Succeed;
871 Fail_1:
872 Py_DECREF(result);
873 Fail_2:
874 result = NULL;
875 Succeed:
876 assert(seqs);
877 for (i = 0; i < n; ++i)
878 Py_XDECREF(seqs[i].it);
879 PyMem_DEL(seqs);
880 return result;
883 static char map_doc[] =
884 "map(function, sequence[, sequence, ...]) -> list\n\
886 Return a list of the results of applying the function to the items of\n\
887 the argument sequence(s). If more than one sequence is given, the\n\
888 function is called with an argument list consisting of the corresponding\n\
889 item of each sequence, substituting None for missing values when not all\n\
890 sequences have the same length. If the function is None, return a list of\n\
891 the items of the sequence (or a list of tuples if more than one sequence).";
894 static PyObject *
895 builtin_setattr(PyObject *self, PyObject *args)
897 PyObject *v;
898 PyObject *name;
899 PyObject *value;
901 if (!PyArg_ParseTuple(args, "OOO:setattr", &v, &name, &value))
902 return NULL;
903 if (PyObject_SetAttr(v, name, value) != 0)
904 return NULL;
905 Py_INCREF(Py_None);
906 return Py_None;
909 static char setattr_doc[] =
910 "setattr(object, name, value)\n\
912 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
913 ``x.y = v''.";
916 static PyObject *
917 builtin_delattr(PyObject *self, PyObject *args)
919 PyObject *v;
920 PyObject *name;
922 if (!PyArg_ParseTuple(args, "OO:delattr", &v, &name))
923 return NULL;
924 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
925 return NULL;
926 Py_INCREF(Py_None);
927 return Py_None;
930 static char delattr_doc[] =
931 "delattr(object, name)\n\
933 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
934 ``del x.y''.";
937 static PyObject *
938 builtin_hash(PyObject *self, PyObject *v)
940 long x;
942 x = PyObject_Hash(v);
943 if (x == -1)
944 return NULL;
945 return PyInt_FromLong(x);
948 static char hash_doc[] =
949 "hash(object) -> integer\n\
951 Return a hash value for the object. Two objects with the same value have\n\
952 the same hash value. The reverse is not necessarily true, but likely.";
955 static PyObject *
956 builtin_hex(PyObject *self, PyObject *v)
958 PyNumberMethods *nb;
960 if ((nb = v->ob_type->tp_as_number) == NULL ||
961 nb->nb_hex == NULL) {
962 PyErr_SetString(PyExc_TypeError,
963 "hex() argument can't be converted to hex");
964 return NULL;
966 return (*nb->nb_hex)(v);
969 static char hex_doc[] =
970 "hex(number) -> string\n\
972 Return the hexadecimal representation of an integer or long integer.";
975 static PyObject *builtin_raw_input(PyObject *, PyObject *);
977 static PyObject *
978 builtin_input(PyObject *self, PyObject *args)
980 PyObject *line;
981 char *str;
982 PyObject *res;
983 PyObject *globals, *locals;
985 line = builtin_raw_input(self, args);
986 if (line == NULL)
987 return line;
988 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
989 return NULL;
990 while (*str == ' ' || *str == '\t')
991 str++;
992 globals = PyEval_GetGlobals();
993 locals = PyEval_GetLocals();
994 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
995 if (PyDict_SetItemString(globals, "__builtins__",
996 PyEval_GetBuiltins()) != 0)
997 return NULL;
999 res = PyRun_String(str, Py_eval_input, globals, locals);
1000 Py_DECREF(line);
1001 return res;
1004 static char input_doc[] =
1005 "input([prompt]) -> value\n\
1007 Equivalent to eval(raw_input(prompt)).";
1010 static PyObject *
1011 builtin_intern(PyObject *self, PyObject *args)
1013 PyObject *s;
1014 if (!PyArg_ParseTuple(args, "S:intern", &s))
1015 return NULL;
1016 Py_INCREF(s);
1017 PyString_InternInPlace(&s);
1018 return s;
1021 static char intern_doc[] =
1022 "intern(string) -> string\n\
1024 ``Intern'' the given string. This enters the string in the (global)\n\
1025 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1026 Return the string itself or the previously interned string object with the\n\
1027 same value.";
1030 static PyObject *
1031 builtin_iter(PyObject *self, PyObject *args)
1033 PyObject *v, *w = NULL;
1035 if (!PyArg_ParseTuple(args, "O|O:iter", &v, &w))
1036 return NULL;
1037 if (w == NULL)
1038 return PyObject_GetIter(v);
1039 if (!PyCallable_Check(v)) {
1040 PyErr_SetString(PyExc_TypeError,
1041 "iter(v, w): v must be callable");
1042 return NULL;
1044 return PyCallIter_New(v, w);
1047 static char iter_doc[] =
1048 "iter(collection) -> iterator\n\
1049 iter(callable, sentinel) -> iterator\n\
1051 Get an iterator from an object. In the first form, the argument must\n\
1052 supply its own iterator, or be a sequence.\n\
1053 In the second form, the callable is called until it returns the sentinel.";
1056 static PyObject *
1057 builtin_len(PyObject *self, PyObject *v)
1059 long res;
1061 res = PyObject_Size(v);
1062 if (res < 0 && PyErr_Occurred())
1063 return NULL;
1064 return PyInt_FromLong(res);
1067 static char len_doc[] =
1068 "len(object) -> integer\n\
1070 Return the number of items of a sequence or mapping.";
1073 static PyObject *
1074 builtin_slice(PyObject *self, PyObject *args)
1076 PyObject *start, *stop, *step;
1078 start = stop = step = NULL;
1080 if (!PyArg_ParseTuple(args, "O|OO:slice", &start, &stop, &step))
1081 return NULL;
1083 /* This swapping of stop and start is to maintain similarity with
1084 range(). */
1085 if (stop == NULL) {
1086 stop = start;
1087 start = NULL;
1089 return PySlice_New(start, stop, step);
1092 static char slice_doc[] =
1093 "slice([start,] stop[, step]) -> slice object\n\
1095 Create a slice object. This is used for slicing by the Numeric extensions.";
1098 static PyObject *
1099 builtin_locals(PyObject *self)
1101 PyObject *d;
1103 d = PyEval_GetLocals();
1104 Py_INCREF(d);
1105 return d;
1108 static char locals_doc[] =
1109 "locals() -> dictionary\n\
1111 Return the dictionary containing the current scope's local variables.";
1114 static PyObject *
1115 min_max(PyObject *args, int op)
1117 PyObject *v, *w, *x, *it;
1119 if (PyTuple_Size(args) > 1)
1120 v = args;
1121 else if (!PyArg_ParseTuple(args, "O:min/max", &v))
1122 return NULL;
1124 it = PyObject_GetIter(v);
1125 if (it == NULL)
1126 return NULL;
1128 w = NULL; /* the result */
1129 for (;;) {
1130 x = PyIter_Next(it);
1131 if (x == NULL) {
1132 if (PyErr_Occurred()) {
1133 Py_XDECREF(w);
1134 Py_DECREF(it);
1135 return NULL;
1137 break;
1140 if (w == NULL)
1141 w = x;
1142 else {
1143 int cmp = PyObject_RichCompareBool(x, w, op);
1144 if (cmp > 0) {
1145 Py_DECREF(w);
1146 w = x;
1148 else if (cmp < 0) {
1149 Py_DECREF(x);
1150 Py_DECREF(w);
1151 Py_DECREF(it);
1152 return NULL;
1154 else
1155 Py_DECREF(x);
1158 if (w == NULL)
1159 PyErr_SetString(PyExc_ValueError,
1160 "min() or max() arg is an empty sequence");
1161 Py_DECREF(it);
1162 return w;
1165 static PyObject *
1166 builtin_min(PyObject *self, PyObject *v)
1168 return min_max(v, Py_LT);
1171 static char min_doc[] =
1172 "min(sequence) -> value\n\
1173 min(a, b, c, ...) -> value\n\
1175 With a single sequence argument, return its smallest item.\n\
1176 With two or more arguments, return the smallest argument.";
1179 static PyObject *
1180 builtin_max(PyObject *self, PyObject *v)
1182 return min_max(v, Py_GT);
1185 static char max_doc[] =
1186 "max(sequence) -> value\n\
1187 max(a, b, c, ...) -> value\n\
1189 With a single sequence argument, return its largest item.\n\
1190 With two or more arguments, return the largest argument.";
1193 static PyObject *
1194 builtin_oct(PyObject *self, PyObject *v)
1196 PyNumberMethods *nb;
1198 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1199 nb->nb_oct == NULL) {
1200 PyErr_SetString(PyExc_TypeError,
1201 "oct() argument can't be converted to oct");
1202 return NULL;
1204 return (*nb->nb_oct)(v);
1207 static char oct_doc[] =
1208 "oct(number) -> string\n\
1210 Return the octal representation of an integer or long integer.";
1213 static PyObject *
1214 builtin_ord(PyObject *self, PyObject* obj)
1216 long ord;
1217 int size;
1219 if (PyString_Check(obj)) {
1220 size = PyString_GET_SIZE(obj);
1221 if (size == 1) {
1222 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1223 return PyInt_FromLong(ord);
1225 #ifdef Py_USING_UNICODE
1226 } else if (PyUnicode_Check(obj)) {
1227 size = PyUnicode_GET_SIZE(obj);
1228 if (size == 1) {
1229 ord = (long)*PyUnicode_AS_UNICODE(obj);
1230 return PyInt_FromLong(ord);
1232 #endif
1233 } else {
1234 PyErr_Format(PyExc_TypeError,
1235 "ord() expected string of length 1, but " \
1236 "%.200s found", obj->ob_type->tp_name);
1237 return NULL;
1240 PyErr_Format(PyExc_TypeError,
1241 "ord() expected a character, "
1242 "but string of length %d found",
1243 size);
1244 return NULL;
1247 static char ord_doc[] =
1248 "ord(c) -> integer\n\
1250 Return the integer ordinal of a one-character string.";
1253 static PyObject *
1254 builtin_pow(PyObject *self, PyObject *args)
1256 PyObject *v, *w, *z = Py_None;
1258 if (!PyArg_ParseTuple(args, "OO|O:pow", &v, &w, &z))
1259 return NULL;
1260 return PyNumber_Power(v, w, z);
1263 static char pow_doc[] =
1264 "pow(x, y[, z]) -> number\n\
1266 With two arguments, equivalent to x**y. With three arguments,\n\
1267 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).";
1270 /* Return number of items in range/xrange (lo, hi, step). step > 0
1271 * required. Return a value < 0 if & only if the true value is too
1272 * large to fit in a signed long.
1274 static long
1275 get_len_of_range(long lo, long hi, long step)
1277 /* -------------------------------------------------------------
1278 If lo >= hi, the range is empty.
1279 Else if n values are in the range, the last one is
1280 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1281 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1282 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1283 the RHS is non-negative and so truncation is the same as the
1284 floor. Letting M be the largest positive long, the worst case
1285 for the RHS numerator is hi=M, lo=-M-1, and then
1286 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1287 precision to compute the RHS exactly.
1288 ---------------------------------------------------------------*/
1289 long n = 0;
1290 if (lo < hi) {
1291 unsigned long uhi = (unsigned long)hi;
1292 unsigned long ulo = (unsigned long)lo;
1293 unsigned long diff = uhi - ulo - 1;
1294 n = (long)(diff / (unsigned long)step + 1);
1296 return n;
1299 static PyObject *
1300 builtin_range(PyObject *self, PyObject *args)
1302 long ilow = 0, ihigh = 0, istep = 1;
1303 long bign;
1304 int i, n;
1306 PyObject *v;
1308 if (PyTuple_Size(args) <= 1) {
1309 if (!PyArg_ParseTuple(args,
1310 "l;range() requires 1-3 int arguments",
1311 &ihigh))
1312 return NULL;
1314 else {
1315 if (!PyArg_ParseTuple(args,
1316 "ll|l;range() requires 1-3 int arguments",
1317 &ilow, &ihigh, &istep))
1318 return NULL;
1320 if (istep == 0) {
1321 PyErr_SetString(PyExc_ValueError, "range() arg 3 must not be zero");
1322 return NULL;
1324 if (istep > 0)
1325 bign = get_len_of_range(ilow, ihigh, istep);
1326 else
1327 bign = get_len_of_range(ihigh, ilow, -istep);
1328 n = (int)bign;
1329 if (bign < 0 || (long)n != bign) {
1330 PyErr_SetString(PyExc_OverflowError,
1331 "range() result has too many items");
1332 return NULL;
1334 v = PyList_New(n);
1335 if (v == NULL)
1336 return NULL;
1337 for (i = 0; i < n; i++) {
1338 PyObject *w = PyInt_FromLong(ilow);
1339 if (w == NULL) {
1340 Py_DECREF(v);
1341 return NULL;
1343 PyList_SET_ITEM(v, i, w);
1344 ilow += istep;
1346 return v;
1349 static char range_doc[] =
1350 "range([start,] stop[, step]) -> list of integers\n\
1352 Return a list containing an arithmetic progression of integers.\n\
1353 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1354 When step is given, it specifies the increment (or decrement).\n\
1355 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1356 These are exactly the valid indices for a list of 4 elements.";
1359 static PyObject *
1360 builtin_xrange(PyObject *self, PyObject *args)
1362 long ilow = 0, ihigh = 0, istep = 1;
1363 long n;
1365 if (PyTuple_Size(args) <= 1) {
1366 if (!PyArg_ParseTuple(args,
1367 "l;xrange() requires 1-3 int arguments",
1368 &ihigh))
1369 return NULL;
1371 else {
1372 if (!PyArg_ParseTuple(args,
1373 "ll|l;xrange() requires 1-3 int arguments",
1374 &ilow, &ihigh, &istep))
1375 return NULL;
1377 if (istep == 0) {
1378 PyErr_SetString(PyExc_ValueError, "xrange() arg 3 must not be zero");
1379 return NULL;
1381 if (istep > 0)
1382 n = get_len_of_range(ilow, ihigh, istep);
1383 else
1384 n = get_len_of_range(ihigh, ilow, -istep);
1385 if (n < 0) {
1386 PyErr_SetString(PyExc_OverflowError,
1387 "xrange() result has too many items");
1388 return NULL;
1390 return PyRange_New(ilow, n, istep, 1);
1393 static char xrange_doc[] =
1394 "xrange([start,] stop[, step]) -> xrange object\n\
1396 Like range(), but instead of returning a list, returns an object that\n\
1397 generates the numbers in the range on demand. This is slightly slower\n\
1398 than range() but more memory efficient.";
1401 static PyObject *
1402 builtin_raw_input(PyObject *self, PyObject *args)
1404 PyObject *v = NULL;
1405 PyObject *f;
1407 if (!PyArg_ParseTuple(args, "|O:[raw_]input", &v))
1408 return NULL;
1409 if (PyFile_AsFile(PySys_GetObject("stdin")) == stdin &&
1410 PyFile_AsFile(PySys_GetObject("stdout")) == stdout &&
1411 isatty(fileno(stdin)) && isatty(fileno(stdout))) {
1412 PyObject *po;
1413 char *prompt;
1414 char *s;
1415 PyObject *result;
1416 if (v != NULL) {
1417 po = PyObject_Str(v);
1418 if (po == NULL)
1419 return NULL;
1420 prompt = PyString_AsString(po);
1421 if (prompt == NULL)
1422 return NULL;
1424 else {
1425 po = NULL;
1426 prompt = "";
1428 s = PyOS_Readline(prompt);
1429 Py_XDECREF(po);
1430 if (s == NULL) {
1431 PyErr_SetNone(PyExc_KeyboardInterrupt);
1432 return NULL;
1434 if (*s == '\0') {
1435 PyErr_SetNone(PyExc_EOFError);
1436 result = NULL;
1438 else { /* strip trailing '\n' */
1439 size_t len = strlen(s);
1440 if (len > INT_MAX) {
1441 PyErr_SetString(PyExc_OverflowError, "input too long");
1442 result = NULL;
1444 else {
1445 result = PyString_FromStringAndSize(s, (int)(len-1));
1448 PyMem_FREE(s);
1449 return result;
1451 if (v != NULL) {
1452 f = PySys_GetObject("stdout");
1453 if (f == NULL) {
1454 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1455 return NULL;
1457 if (Py_FlushLine() != 0 ||
1458 PyFile_WriteObject(v, f, Py_PRINT_RAW) != 0)
1459 return NULL;
1461 f = PySys_GetObject("stdin");
1462 if (f == NULL) {
1463 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdin");
1464 return NULL;
1466 return PyFile_GetLine(f, -1);
1469 static char raw_input_doc[] =
1470 "raw_input([prompt]) -> string\n\
1472 Read a string from standard input. The trailing newline is stripped.\n\
1473 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1474 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1475 is printed without a trailing newline before reading.";
1478 static PyObject *
1479 builtin_reduce(PyObject *self, PyObject *args)
1481 PyObject *seq, *func, *result = NULL, *it;
1483 if (!PyArg_ParseTuple(args, "OO|O:reduce", &func, &seq, &result))
1484 return NULL;
1485 if (result != NULL)
1486 Py_INCREF(result);
1488 it = PyObject_GetIter(seq);
1489 if (it == NULL) {
1490 PyErr_SetString(PyExc_TypeError,
1491 "reduce() arg 2 must support iteration");
1492 Py_XDECREF(result);
1493 return NULL;
1496 if ((args = PyTuple_New(2)) == NULL)
1497 goto Fail;
1499 for (;;) {
1500 PyObject *op2;
1502 if (args->ob_refcnt > 1) {
1503 Py_DECREF(args);
1504 if ((args = PyTuple_New(2)) == NULL)
1505 goto Fail;
1508 op2 = PyIter_Next(it);
1509 if (op2 == NULL) {
1510 if (PyErr_Occurred())
1511 goto Fail;
1512 break;
1515 if (result == NULL)
1516 result = op2;
1517 else {
1518 PyTuple_SetItem(args, 0, result);
1519 PyTuple_SetItem(args, 1, op2);
1520 if ((result = PyEval_CallObject(func, args)) == NULL)
1521 goto Fail;
1525 Py_DECREF(args);
1527 if (result == NULL)
1528 PyErr_SetString(PyExc_TypeError,
1529 "reduce() of empty sequence with no initial value");
1531 Py_DECREF(it);
1532 return result;
1534 Fail:
1535 Py_XDECREF(args);
1536 Py_XDECREF(result);
1537 Py_DECREF(it);
1538 return NULL;
1541 static char reduce_doc[] =
1542 "reduce(function, sequence[, initial]) -> value\n\
1544 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1545 from left to right, so as to reduce the sequence to a single value.\n\
1546 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1547 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1548 of the sequence in the calculation, and serves as a default when the\n\
1549 sequence is empty.";
1552 static PyObject *
1553 builtin_reload(PyObject *self, PyObject *v)
1555 return PyImport_ReloadModule(v);
1558 static char reload_doc[] =
1559 "reload(module) -> module\n\
1561 Reload the module. The module must have been successfully imported before.";
1564 static PyObject *
1565 builtin_repr(PyObject *self, PyObject *v)
1567 return PyObject_Repr(v);
1570 static char repr_doc[] =
1571 "repr(object) -> string\n\
1573 Return the canonical string representation of the object.\n\
1574 For most object types, eval(repr(object)) == object.";
1577 static PyObject *
1578 builtin_round(PyObject *self, PyObject *args)
1580 double x;
1581 double f;
1582 int ndigits = 0;
1583 int i;
1585 if (!PyArg_ParseTuple(args, "d|i:round", &x, &ndigits))
1586 return NULL;
1587 f = 1.0;
1588 i = abs(ndigits);
1589 while (--i >= 0)
1590 f = f*10.0;
1591 if (ndigits < 0)
1592 x /= f;
1593 else
1594 x *= f;
1595 if (x >= 0.0)
1596 x = floor(x + 0.5);
1597 else
1598 x = ceil(x - 0.5);
1599 if (ndigits < 0)
1600 x *= f;
1601 else
1602 x /= f;
1603 return PyFloat_FromDouble(x);
1606 static char round_doc[] =
1607 "round(number[, ndigits]) -> floating point number\n\
1609 Round a number to a given precision in decimal digits (default 0 digits).\n\
1610 This always returns a floating point number. Precision may be negative.";
1613 static PyObject *
1614 builtin_vars(PyObject *self, PyObject *args)
1616 PyObject *v = NULL;
1617 PyObject *d;
1619 if (!PyArg_ParseTuple(args, "|O:vars", &v))
1620 return NULL;
1621 if (v == NULL) {
1622 d = PyEval_GetLocals();
1623 if (d == NULL) {
1624 if (!PyErr_Occurred())
1625 PyErr_SetString(PyExc_SystemError,
1626 "no locals!?");
1628 else
1629 Py_INCREF(d);
1631 else {
1632 d = PyObject_GetAttrString(v, "__dict__");
1633 if (d == NULL) {
1634 PyErr_SetString(PyExc_TypeError,
1635 "vars() argument must have __dict__ attribute");
1636 return NULL;
1639 return d;
1642 static char vars_doc[] =
1643 "vars([object]) -> dictionary\n\
1645 Without arguments, equivalent to locals().\n\
1646 With an argument, equivalent to object.__dict__.";
1648 static PyObject *
1649 builtin_isinstance(PyObject *self, PyObject *args)
1651 PyObject *inst;
1652 PyObject *cls;
1653 int retval;
1655 if (!PyArg_ParseTuple(args, "OO:isinstance", &inst, &cls))
1656 return NULL;
1658 retval = PyObject_IsInstance(inst, cls);
1659 if (retval < 0)
1660 return NULL;
1661 return PyInt_FromLong(retval);
1664 static char isinstance_doc[] =
1665 "isinstance(object, class-or-type-or-tuple) -> Boolean\n\
1667 Return whether an object is an instance of a class or of a subclass thereof.\n\
1668 With a type as second argument, return whether that is the object's type.\n\
1669 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
1670 isinstance(x, A) or isinstance(x, B) or ... (etc.).";
1673 static PyObject *
1674 builtin_issubclass(PyObject *self, PyObject *args)
1676 PyObject *derived;
1677 PyObject *cls;
1678 int retval;
1680 if (!PyArg_ParseTuple(args, "OO:issubclass", &derived, &cls))
1681 return NULL;
1683 retval = PyObject_IsSubclass(derived, cls);
1684 if (retval < 0)
1685 return NULL;
1686 return PyInt_FromLong(retval);
1689 static char issubclass_doc[] =
1690 "issubclass(C, B) -> Boolean\n\
1692 Return whether class C is a subclass (i.e., a derived class) of class B.";
1695 static PyObject*
1696 builtin_zip(PyObject *self, PyObject *args)
1698 PyObject *ret;
1699 int itemsize = PySequence_Length(args);
1700 int i;
1701 PyObject *itlist; /* tuple of iterators */
1703 if (itemsize < 1) {
1704 PyErr_SetString(PyExc_TypeError,
1705 "zip() requires at least one sequence");
1706 return NULL;
1708 /* args must be a tuple */
1709 assert(PyTuple_Check(args));
1711 /* allocate result list */
1712 if ((ret = PyList_New(0)) == NULL)
1713 return NULL;
1715 /* obtain iterators */
1716 itlist = PyTuple_New(itemsize);
1717 if (itlist == NULL)
1718 goto Fail_ret;
1719 for (i = 0; i < itemsize; ++i) {
1720 PyObject *item = PyTuple_GET_ITEM(args, i);
1721 PyObject *it = PyObject_GetIter(item);
1722 if (it == NULL) {
1723 if (PyErr_ExceptionMatches(PyExc_TypeError))
1724 PyErr_Format(PyExc_TypeError,
1725 "zip argument #%d must support iteration",
1726 i+1);
1727 goto Fail_ret_itlist;
1729 PyTuple_SET_ITEM(itlist, i, it);
1732 /* build result into ret list */
1733 for (;;) {
1734 int status;
1735 PyObject *next = PyTuple_New(itemsize);
1736 if (!next)
1737 goto Fail_ret_itlist;
1739 for (i = 0; i < itemsize; i++) {
1740 PyObject *it = PyTuple_GET_ITEM(itlist, i);
1741 PyObject *item = PyIter_Next(it);
1742 if (!item) {
1743 if (PyErr_Occurred()) {
1744 Py_DECREF(ret);
1745 ret = NULL;
1747 Py_DECREF(next);
1748 Py_DECREF(itlist);
1749 return ret;
1751 PyTuple_SET_ITEM(next, i, item);
1754 status = PyList_Append(ret, next);
1755 Py_DECREF(next);
1756 if (status < 0)
1757 goto Fail_ret_itlist;
1760 Fail_ret_itlist:
1761 Py_DECREF(itlist);
1762 Fail_ret:
1763 Py_DECREF(ret);
1764 return NULL;
1768 static char zip_doc[] =
1769 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
1771 Return a list of tuples, where each tuple contains the i-th element\n\
1772 from each of the argument sequences. The returned list is truncated\n\
1773 in length to the length of the shortest argument sequence.";
1776 static PyMethodDef builtin_methods[] = {
1777 {"__import__", builtin___import__, METH_VARARGS, import_doc},
1778 {"abs", builtin_abs, METH_O, abs_doc},
1779 {"apply", builtin_apply, METH_VARARGS, apply_doc},
1780 {"buffer", builtin_buffer, METH_VARARGS, buffer_doc},
1781 {"callable", builtin_callable, METH_O, callable_doc},
1782 {"chr", builtin_chr, METH_VARARGS, chr_doc},
1783 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
1784 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
1785 {"compile", builtin_compile, METH_VARARGS, compile_doc},
1786 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
1787 {"dir", builtin_dir, METH_VARARGS, dir_doc},
1788 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
1789 {"eval", builtin_eval, METH_VARARGS, eval_doc},
1790 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
1791 {"filter", builtin_filter, METH_VARARGS, filter_doc},
1792 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
1793 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
1794 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
1795 {"hash", builtin_hash, METH_O, hash_doc},
1796 {"hex", builtin_hex, METH_O, hex_doc},
1797 {"id", builtin_id, METH_O, id_doc},
1798 {"input", builtin_input, METH_VARARGS, input_doc},
1799 {"intern", builtin_intern, METH_VARARGS, intern_doc},
1800 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
1801 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
1802 {"iter", builtin_iter, METH_VARARGS, iter_doc},
1803 {"len", builtin_len, METH_O, len_doc},
1804 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
1805 {"map", builtin_map, METH_VARARGS, map_doc},
1806 {"max", builtin_max, METH_VARARGS, max_doc},
1807 {"min", builtin_min, METH_VARARGS, min_doc},
1808 {"oct", builtin_oct, METH_O, oct_doc},
1809 {"ord", builtin_ord, METH_O, ord_doc},
1810 {"pow", builtin_pow, METH_VARARGS, pow_doc},
1811 {"range", builtin_range, METH_VARARGS, range_doc},
1812 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
1813 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
1814 {"reload", builtin_reload, METH_O, reload_doc},
1815 {"repr", builtin_repr, METH_O, repr_doc},
1816 {"round", builtin_round, METH_VARARGS, round_doc},
1817 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
1818 {"slice", builtin_slice, METH_VARARGS, slice_doc},
1819 #ifdef Py_USING_UNICODE
1820 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
1821 #endif
1822 {"vars", builtin_vars, METH_VARARGS, vars_doc},
1823 {"xrange", builtin_xrange, METH_VARARGS, xrange_doc},
1824 {"zip", builtin_zip, METH_VARARGS, zip_doc},
1825 {NULL, NULL},
1828 static char builtin_doc[] =
1829 "Built-in functions, exceptions, and other objects.\n\
1831 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.";
1833 PyObject *
1834 _PyBuiltin_Init(void)
1836 PyObject *mod, *dict, *debug;
1837 mod = Py_InitModule4("__builtin__", builtin_methods,
1838 builtin_doc, (PyObject *)NULL,
1839 PYTHON_API_VERSION);
1840 if (mod == NULL)
1841 return NULL;
1842 dict = PyModule_GetDict(mod);
1844 #define SETBUILTIN(NAME, OBJECT) \
1845 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
1846 return NULL
1848 SETBUILTIN("None", Py_None);
1849 SETBUILTIN("Ellipsis", Py_Ellipsis);
1850 SETBUILTIN("NotImplemented", Py_NotImplemented);
1851 SETBUILTIN("classmethod", &PyClassMethod_Type);
1852 #ifndef WITHOUT_COMPLEX
1853 SETBUILTIN("complex", &PyComplex_Type);
1854 #endif
1855 SETBUILTIN("dict", &PyDict_Type);
1856 SETBUILTIN("float", &PyFloat_Type);
1857 SETBUILTIN("property", &PyProperty_Type);
1858 SETBUILTIN("int", &PyInt_Type);
1859 SETBUILTIN("list", &PyList_Type);
1860 SETBUILTIN("long", &PyLong_Type);
1861 SETBUILTIN("object", &PyBaseObject_Type);
1862 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
1863 SETBUILTIN("str", &PyString_Type);
1864 SETBUILTIN("super", &PySuper_Type);
1865 SETBUILTIN("tuple", &PyTuple_Type);
1866 SETBUILTIN("type", &PyType_Type);
1868 /* Note that open() is just an alias of file(). */
1869 SETBUILTIN("open", &PyFile_Type);
1870 SETBUILTIN("file", &PyFile_Type);
1871 #ifdef Py_USING_UNICODE
1872 SETBUILTIN("unicode", &PyUnicode_Type);
1873 #endif
1874 debug = PyInt_FromLong(Py_OptimizeFlag == 0);
1875 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
1876 Py_XDECREF(debug);
1877 return NULL;
1879 Py_XDECREF(debug);
1881 return mod;
1882 #undef SETBUILTIN
1885 /* Helper for filter(): filter a tuple through a function */
1887 static PyObject *
1888 filtertuple(PyObject *func, PyObject *tuple)
1890 PyObject *result;
1891 register int i, j;
1892 int len = PyTuple_Size(tuple);
1894 if (len == 0) {
1895 Py_INCREF(tuple);
1896 return tuple;
1899 if ((result = PyTuple_New(len)) == NULL)
1900 return NULL;
1902 for (i = j = 0; i < len; ++i) {
1903 PyObject *item, *good;
1904 int ok;
1906 if ((item = PyTuple_GetItem(tuple, i)) == NULL)
1907 goto Fail_1;
1908 if (func == Py_None) {
1909 Py_INCREF(item);
1910 good = item;
1912 else {
1913 PyObject *arg = Py_BuildValue("(O)", item);
1914 if (arg == NULL)
1915 goto Fail_1;
1916 good = PyEval_CallObject(func, arg);
1917 Py_DECREF(arg);
1918 if (good == NULL)
1919 goto Fail_1;
1921 ok = PyObject_IsTrue(good);
1922 Py_DECREF(good);
1923 if (ok) {
1924 Py_INCREF(item);
1925 if (PyTuple_SetItem(result, j++, item) < 0)
1926 goto Fail_1;
1930 if (_PyTuple_Resize(&result, j) < 0)
1931 return NULL;
1933 return result;
1935 Fail_1:
1936 Py_DECREF(result);
1937 return NULL;
1941 /* Helper for filter(): filter a string through a function */
1943 static PyObject *
1944 filterstring(PyObject *func, PyObject *strobj)
1946 PyObject *result;
1947 register int i, j;
1948 int len = PyString_Size(strobj);
1950 if (func == Py_None) {
1951 /* No character is ever false -- share input string */
1952 Py_INCREF(strobj);
1953 return strobj;
1955 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
1956 return NULL;
1958 for (i = j = 0; i < len; ++i) {
1959 PyObject *item, *arg, *good;
1960 int ok;
1962 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
1963 if (item == NULL)
1964 goto Fail_1;
1965 arg = Py_BuildValue("(O)", item);
1966 if (arg == NULL) {
1967 Py_DECREF(item);
1968 goto Fail_1;
1970 good = PyEval_CallObject(func, arg);
1971 Py_DECREF(arg);
1972 if (good == NULL) {
1973 Py_DECREF(item);
1974 goto Fail_1;
1976 ok = PyObject_IsTrue(good);
1977 Py_DECREF(good);
1978 if (ok)
1979 PyString_AS_STRING((PyStringObject *)result)[j++] =
1980 PyString_AS_STRING((PyStringObject *)item)[0];
1981 Py_DECREF(item);
1984 if (j < len && _PyString_Resize(&result, j) < 0)
1985 return NULL;
1987 return result;
1989 Fail_1:
1990 Py_DECREF(result);
1991 return NULL;