- Got rid of newmodule.c
[python/dscho.git] / Python / bltinmodule.c
blob712639107df7785d7fe9f8776d78f7cde3b3b7b8
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 RISCOS
13 #include "unixstuff.h"
14 #endif
16 /* The default encoding used by the platform file system APIs
17 Can remain NULL for all platforms that don't have such a concept
19 #if defined(MS_WIN32) && defined(HAVE_USABLE_WCHAR_T)
20 const char *Py_FileSystemDefaultEncoding = "mbcs";
21 #else
22 const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
23 #endif
25 /* Forward */
26 static PyObject *filterstring(PyObject *, PyObject *);
27 static PyObject *filtertuple (PyObject *, PyObject *);
29 static PyObject *
30 builtin___import__(PyObject *self, PyObject *args)
32 char *name;
33 PyObject *globals = NULL;
34 PyObject *locals = NULL;
35 PyObject *fromlist = NULL;
37 if (!PyArg_ParseTuple(args, "s|OOO:__import__",
38 &name, &globals, &locals, &fromlist))
39 return NULL;
40 return PyImport_ImportModuleEx(name, globals, locals, fromlist);
43 PyDoc_STRVAR(import_doc,
44 "__import__(name, globals, locals, fromlist) -> module\n\
45 \n\
46 Import a module. The globals are only used to determine the context;\n\
47 they are not modified. The locals are currently unused. The fromlist\n\
48 should be a list of names to emulate ``from name import ...'', or an\n\
49 empty list to emulate ``import name''.\n\
50 When importing a module from a package, note that __import__('A.B', ...)\n\
51 returns package A when fromlist is empty, but its submodule B when\n\
52 fromlist is not empty.");
55 static PyObject *
56 builtin_abs(PyObject *self, PyObject *v)
58 return PyNumber_Absolute(v);
61 PyDoc_STRVAR(abs_doc,
62 "abs(number) -> number\n\
63 \n\
64 Return the absolute value of the argument.");
67 static PyObject *
68 builtin_apply(PyObject *self, PyObject *args)
70 PyObject *func, *alist = NULL, *kwdict = NULL;
71 PyObject *t = NULL, *retval = NULL;
73 if (!PyArg_ParseTuple(args, "O|OO:apply", &func, &alist, &kwdict))
74 return NULL;
75 if (alist != NULL) {
76 if (!PyTuple_Check(alist)) {
77 if (!PySequence_Check(alist)) {
78 PyErr_Format(PyExc_TypeError,
79 "apply() arg 2 expect sequence, found %s",
80 alist->ob_type->tp_name);
81 return NULL;
83 t = PySequence_Tuple(alist);
84 if (t == NULL)
85 return NULL;
86 alist = t;
89 if (kwdict != NULL && !PyDict_Check(kwdict)) {
90 PyErr_Format(PyExc_TypeError,
91 "apply() arg 3 expected dictionary, found %s",
92 kwdict->ob_type->tp_name);
93 goto finally;
95 retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
96 finally:
97 Py_XDECREF(t);
98 return retval;
101 PyDoc_STRVAR(apply_doc,
102 "apply(object[, args[, kwargs]]) -> value\n\
104 Call a callable object with positional arguments taken from the tuple args,\n\
105 and keyword arguments taken from the optional dictionary kwargs.\n\
106 Note that classes are callable, as are instances with a __call__() method.");
109 static PyObject *
110 builtin_callable(PyObject *self, PyObject *v)
112 return PyBool_FromLong((long)PyCallable_Check(v));
115 PyDoc_STRVAR(callable_doc,
116 "callable(object) -> bool\n\
118 Return whether the object is callable (i.e., some kind of function).\n\
119 Note that classes are callable, as are instances with a __call__() method.");
122 static PyObject *
123 builtin_filter(PyObject *self, PyObject *args)
125 PyObject *func, *seq, *result, *it;
126 int len; /* guess for result list size */
127 register int j;
129 if (!PyArg_ParseTuple(args, "OO:filter", &func, &seq))
130 return NULL;
132 /* Strings and tuples return a result of the same type. */
133 if (PyString_Check(seq))
134 return filterstring(func, seq);
135 if (PyTuple_Check(seq))
136 return filtertuple(func, seq);
138 /* Get iterator. */
139 it = PyObject_GetIter(seq);
140 if (it == NULL)
141 return NULL;
143 /* Guess a result list size. */
144 len = -1; /* unknown */
145 if (PySequence_Check(seq) &&
146 seq->ob_type->tp_as_sequence->sq_length) {
147 len = PySequence_Size(seq);
148 if (len < 0)
149 PyErr_Clear();
151 if (len < 0)
152 len = 8; /* arbitrary */
154 /* Get a result list. */
155 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
156 /* Eww - can modify the list in-place. */
157 Py_INCREF(seq);
158 result = seq;
160 else {
161 result = PyList_New(len);
162 if (result == NULL)
163 goto Fail_it;
166 /* Build the result list. */
167 j = 0;
168 for (;;) {
169 PyObject *item, *good;
170 int ok;
172 item = PyIter_Next(it);
173 if (item == NULL) {
174 if (PyErr_Occurred())
175 goto Fail_result_it;
176 break;
179 if (func == Py_None) {
180 good = item;
181 Py_INCREF(good);
183 else {
184 PyObject *arg = Py_BuildValue("(O)", item);
185 if (arg == NULL) {
186 Py_DECREF(item);
187 goto Fail_result_it;
189 good = PyEval_CallObject(func, arg);
190 Py_DECREF(arg);
191 if (good == NULL) {
192 Py_DECREF(item);
193 goto Fail_result_it;
196 ok = PyObject_IsTrue(good);
197 Py_DECREF(good);
198 if (ok) {
199 if (j < len)
200 PyList_SET_ITEM(result, j, item);
201 else {
202 int status = PyList_Append(result, item);
203 Py_DECREF(item);
204 if (status < 0)
205 goto Fail_result_it;
207 ++j;
209 else
210 Py_DECREF(item);
214 /* Cut back result list if len is too big. */
215 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
216 goto Fail_result_it;
218 Py_DECREF(it);
219 return result;
221 Fail_result_it:
222 Py_DECREF(result);
223 Fail_it:
224 Py_DECREF(it);
225 return NULL;
228 PyDoc_STRVAR(filter_doc,
229 "filter(function or None, sequence) -> list, tuple, or string\n"
230 "\n"
231 "Return those items of sequence for which function(item) is true. If\n"
232 "function is None, return the items that are true. If sequence is a tuple\n"
233 "or string, return the same type, else return a list.");
235 static PyObject *
236 builtin_chr(PyObject *self, PyObject *args)
238 long x;
239 char s[1];
241 if (!PyArg_ParseTuple(args, "l:chr", &x))
242 return NULL;
243 if (x < 0 || x >= 256) {
244 PyErr_SetString(PyExc_ValueError,
245 "chr() arg not in range(256)");
246 return NULL;
248 s[0] = (char)x;
249 return PyString_FromStringAndSize(s, 1);
252 PyDoc_STRVAR(chr_doc,
253 "chr(i) -> character\n\
255 Return a string of one character with ordinal i; 0 <= i < 256.");
258 #ifdef Py_USING_UNICODE
259 static PyObject *
260 builtin_unichr(PyObject *self, PyObject *args)
262 long x;
263 Py_UNICODE s[2];
265 if (!PyArg_ParseTuple(args, "l:unichr", &x))
266 return NULL;
268 #ifdef Py_UNICODE_WIDE
269 if (x < 0 || x > 0x10ffff) {
270 PyErr_SetString(PyExc_ValueError,
271 "unichr() arg not in range(0x110000) "
272 "(wide Python build)");
273 return NULL;
275 #else
276 if (x < 0 || x > 0xffff) {
277 PyErr_SetString(PyExc_ValueError,
278 "unichr() arg not in range(0x10000) "
279 "(narrow Python build)");
280 return NULL;
282 #endif
284 if (x <= 0xffff) {
285 /* UCS-2 character */
286 s[0] = (Py_UNICODE) x;
287 return PyUnicode_FromUnicode(s, 1);
289 else {
290 #ifndef Py_UNICODE_WIDE
291 /* UCS-4 character. store as two surrogate characters */
292 x -= 0x10000L;
293 s[0] = 0xD800 + (Py_UNICODE) (x >> 10);
294 s[1] = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
295 return PyUnicode_FromUnicode(s, 2);
296 #else
297 s[0] = (Py_UNICODE)x;
298 return PyUnicode_FromUnicode(s, 1);
299 #endif
303 PyDoc_STRVAR(unichr_doc,
304 "unichr(i) -> Unicode character\n\
306 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
307 #endif
310 static PyObject *
311 builtin_cmp(PyObject *self, PyObject *args)
313 PyObject *a, *b;
314 int c;
316 if (!PyArg_ParseTuple(args, "OO:cmp", &a, &b))
317 return NULL;
318 if (PyObject_Cmp(a, b, &c) < 0)
319 return NULL;
320 return PyInt_FromLong((long)c);
323 PyDoc_STRVAR(cmp_doc,
324 "cmp(x, y) -> integer\n\
326 Return negative if x<y, zero if x==y, positive if x>y.");
329 static PyObject *
330 builtin_coerce(PyObject *self, PyObject *args)
332 PyObject *v, *w;
333 PyObject *res;
335 if (!PyArg_ParseTuple(args, "OO:coerce", &v, &w))
336 return NULL;
337 if (PyNumber_Coerce(&v, &w) < 0)
338 return NULL;
339 res = Py_BuildValue("(OO)", v, w);
340 Py_DECREF(v);
341 Py_DECREF(w);
342 return res;
345 PyDoc_STRVAR(coerce_doc,
346 "coerce(x, y) -> None or (x1, y1)\n\
348 When x and y can be coerced to values of the same type, return a tuple\n\
349 containing the coerced values. When they can't be coerced, return None.");
352 static PyObject *
353 builtin_compile(PyObject *self, PyObject *args)
355 char *str;
356 char *filename;
357 char *startstr;
358 int start;
359 int dont_inherit = 0;
360 int supplied_flags = 0;
361 PyCompilerFlags cf;
363 if (!PyArg_ParseTuple(args, "sss|ii:compile", &str, &filename,
364 &startstr, &supplied_flags, &dont_inherit))
365 return NULL;
367 if (strcmp(startstr, "exec") == 0)
368 start = Py_file_input;
369 else if (strcmp(startstr, "eval") == 0)
370 start = Py_eval_input;
371 else if (strcmp(startstr, "single") == 0)
372 start = Py_single_input;
373 else {
374 PyErr_SetString(PyExc_ValueError,
375 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
376 return NULL;
379 if (supplied_flags & ~(PyCF_MASK | PyCF_MASK_OBSOLETE)) {
380 PyErr_SetString(PyExc_ValueError,
381 "compile(): unrecognised flags");
382 return NULL;
384 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
386 cf.cf_flags = supplied_flags;
387 if (!dont_inherit) {
388 PyEval_MergeCompilerFlags(&cf);
390 return Py_CompileStringFlags(str, filename, start, &cf);
393 PyDoc_STRVAR(compile_doc,
394 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
396 Compile the source string (a Python module, statement or expression)\n\
397 into a code object that can be executed by the exec statement or eval().\n\
398 The filename will be used for run-time error messages.\n\
399 The mode must be 'exec' to compile a module, 'single' to compile a\n\
400 single (interactive) statement, or 'eval' to compile an expression.\n\
401 The flags argument, if present, controls which future statements influence\n\
402 the compilation of the code.\n\
403 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
404 the effects of any future statements in effect in the code calling\n\
405 compile; if absent or zero these statements do influence the compilation,\n\
406 in addition to any features explicitly specified.");
408 static PyObject *
409 builtin_dir(PyObject *self, PyObject *args)
411 PyObject *arg = NULL;
413 if (!PyArg_ParseTuple(args, "|O:dir", &arg))
414 return NULL;
415 return PyObject_Dir(arg);
418 PyDoc_STRVAR(dir_doc,
419 "dir([object]) -> list of strings\n"
420 "\n"
421 "Return an alphabetized list of names comprising (some of) the attributes\n"
422 "of the given object, and of attributes reachable from it:\n"
423 "\n"
424 "No argument: the names in the current scope.\n"
425 "Module object: the module attributes.\n"
426 "Type or class object: its attributes, and recursively the attributes of\n"
427 " its bases.\n"
428 "Otherwise: its attributes, its class's attributes, and recursively the\n"
429 " attributes of its class's base classes.");
431 static PyObject *
432 builtin_divmod(PyObject *self, PyObject *args)
434 PyObject *v, *w;
436 if (!PyArg_ParseTuple(args, "OO:divmod", &v, &w))
437 return NULL;
438 return PyNumber_Divmod(v, w);
441 PyDoc_STRVAR(divmod_doc,
442 "divmod(x, y) -> (div, mod)\n\
444 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
447 static PyObject *
448 builtin_eval(PyObject *self, PyObject *args)
450 PyObject *cmd;
451 PyObject *globals = Py_None, *locals = Py_None;
452 char *str;
453 PyCompilerFlags cf;
455 if (!PyArg_ParseTuple(args, "O|O!O!:eval",
456 &cmd,
457 &PyDict_Type, &globals,
458 &PyDict_Type, &locals))
459 return NULL;
460 if (globals == Py_None) {
461 globals = PyEval_GetGlobals();
462 if (locals == Py_None)
463 locals = PyEval_GetLocals();
465 else if (locals == Py_None)
466 locals = globals;
468 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
469 if (PyDict_SetItemString(globals, "__builtins__",
470 PyEval_GetBuiltins()) != 0)
471 return NULL;
474 if (PyCode_Check(cmd)) {
475 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
476 PyErr_SetString(PyExc_TypeError,
477 "code object passed to eval() may not contain free variables");
478 return NULL;
480 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
483 if (!PyString_Check(cmd) &&
484 !PyUnicode_Check(cmd)) {
485 PyErr_SetString(PyExc_TypeError,
486 "eval() arg 1 must be a string or code object");
487 return NULL;
489 if (PyString_AsStringAndSize(cmd, &str, NULL))
490 return NULL;
491 while (*str == ' ' || *str == '\t')
492 str++;
494 cf.cf_flags = 0;
495 (void)PyEval_MergeCompilerFlags(&cf);
496 return PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
499 PyDoc_STRVAR(eval_doc,
500 "eval(source[, globals[, locals]]) -> value\n\
502 Evaluate the source in the context of globals and locals.\n\
503 The source may be a string representing a Python expression\n\
504 or a code object as returned by compile().\n\
505 The globals and locals are dictionaries, defaulting to the current\n\
506 globals and locals. If only globals is given, locals defaults to it.");
509 static PyObject *
510 builtin_execfile(PyObject *self, PyObject *args)
512 char *filename;
513 PyObject *globals = Py_None, *locals = Py_None;
514 PyObject *res;
515 FILE* fp = NULL;
516 PyCompilerFlags cf;
517 int exists;
519 if (!PyArg_ParseTuple(args, "s|O!O!:execfile",
520 &filename,
521 &PyDict_Type, &globals,
522 &PyDict_Type, &locals))
523 return NULL;
524 if (globals == Py_None) {
525 globals = PyEval_GetGlobals();
526 if (locals == Py_None)
527 locals = PyEval_GetLocals();
529 else if (locals == Py_None)
530 locals = globals;
531 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
532 if (PyDict_SetItemString(globals, "__builtins__",
533 PyEval_GetBuiltins()) != 0)
534 return NULL;
537 exists = 0;
538 /* Test for existence or directory. */
539 #if defined(PLAN9)
541 Dir *d;
543 if ((d = dirstat(filename))!=nil) {
544 if(d->mode & DMDIR)
545 werrstr("is a directory");
546 else
547 exists = 1;
548 free(d);
551 #elif defined(RISCOS)
552 if (object_exists(filename)) {
553 if (isdir(filename))
554 errno = EISDIR;
555 else
556 exists = 1;
558 #else /* standard Posix */
560 struct stat s;
561 if (stat(filename, &s) == 0) {
562 if (S_ISDIR(s.st_mode))
563 # if defined(PY_OS2) && defined(PYCC_VACPP)
564 errno = EOS2ERR;
565 # else
566 errno = EISDIR;
567 # endif
568 else
569 exists = 1;
572 #endif
574 if (exists) {
575 Py_BEGIN_ALLOW_THREADS
576 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
577 Py_END_ALLOW_THREADS
579 if (fp == NULL) {
580 exists = 0;
584 if (!exists) {
585 PyErr_SetFromErrno(PyExc_IOError);
586 return NULL;
588 cf.cf_flags = 0;
589 if (PyEval_MergeCompilerFlags(&cf))
590 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
591 locals, 1, &cf);
592 else
593 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
594 locals, 1);
595 return res;
598 PyDoc_STRVAR(execfile_doc,
599 "execfile(filename[, globals[, locals]])\n\
601 Read and execute a Python script from a file.\n\
602 The globals and locals are dictionaries, defaulting to the current\n\
603 globals and locals. If only globals is given, locals defaults to it.");
606 static PyObject *
607 builtin_getattr(PyObject *self, PyObject *args)
609 PyObject *v, *result, *dflt = NULL;
610 PyObject *name;
612 if (!PyArg_ParseTuple(args, "OO|O:getattr", &v, &name, &dflt))
613 return NULL;
614 #ifdef Py_USING_UNICODE
615 if (PyUnicode_Check(name)) {
616 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
617 if (name == NULL)
618 return NULL;
620 #endif
622 if (!PyString_Check(name)) {
623 PyErr_SetString(PyExc_TypeError,
624 "attribute name must be string");
625 return NULL;
627 result = PyObject_GetAttr(v, name);
628 if (result == NULL && dflt != NULL &&
629 PyErr_ExceptionMatches(PyExc_AttributeError))
631 PyErr_Clear();
632 Py_INCREF(dflt);
633 result = dflt;
635 return result;
638 PyDoc_STRVAR(getattr_doc,
639 "getattr(object, name[, default]) -> value\n\
641 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
642 When a default argument is given, it is returned when the attribute doesn't\n\
643 exist; without it, an exception is raised in that case.");
646 static PyObject *
647 builtin_globals(PyObject *self)
649 PyObject *d;
651 d = PyEval_GetGlobals();
652 Py_INCREF(d);
653 return d;
656 PyDoc_STRVAR(globals_doc,
657 "globals() -> dictionary\n\
659 Return the dictionary containing the current scope's global variables.");
662 static PyObject *
663 builtin_hasattr(PyObject *self, PyObject *args)
665 PyObject *v;
666 PyObject *name;
668 if (!PyArg_ParseTuple(args, "OO:hasattr", &v, &name))
669 return NULL;
670 #ifdef Py_USING_UNICODE
671 if (PyUnicode_Check(name)) {
672 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
673 if (name == NULL)
674 return NULL;
676 #endif
678 if (!PyString_Check(name)) {
679 PyErr_SetString(PyExc_TypeError,
680 "attribute name must be string");
681 return NULL;
683 v = PyObject_GetAttr(v, name);
684 if (v == NULL) {
685 PyErr_Clear();
686 Py_INCREF(Py_False);
687 return Py_False;
689 Py_DECREF(v);
690 Py_INCREF(Py_True);
691 return Py_True;
694 PyDoc_STRVAR(hasattr_doc,
695 "hasattr(object, name) -> bool\n\
697 Return whether the object has an attribute with the given name.\n\
698 (This is done by calling getattr(object, name) and catching exceptions.)");
701 static PyObject *
702 builtin_id(PyObject *self, PyObject *v)
704 return PyLong_FromVoidPtr(v);
707 PyDoc_STRVAR(id_doc,
708 "id(object) -> integer\n\
710 Return the identity of an object. This is guaranteed to be unique among\n\
711 simultaneously existing objects. (Hint: it's the object's memory address.)");
714 static PyObject *
715 builtin_map(PyObject *self, PyObject *args)
717 typedef struct {
718 PyObject *it; /* the iterator object */
719 int saw_StopIteration; /* bool: did the iterator end? */
720 } sequence;
722 PyObject *func, *result;
723 sequence *seqs = NULL, *sqp;
724 int n, len;
725 register int i, j;
727 n = PyTuple_Size(args);
728 if (n < 2) {
729 PyErr_SetString(PyExc_TypeError,
730 "map() requires at least two args");
731 return NULL;
734 func = PyTuple_GetItem(args, 0);
735 n--;
737 if (func == Py_None && n == 1) {
738 /* map(None, S) is the same as list(S). */
739 return PySequence_List(PyTuple_GetItem(args, 1));
742 /* Get space for sequence descriptors. Must NULL out the iterator
743 * pointers so that jumping to Fail_2 later doesn't see trash.
745 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
746 PyErr_NoMemory();
747 return NULL;
749 for (i = 0; i < n; ++i) {
750 seqs[i].it = (PyObject*)NULL;
751 seqs[i].saw_StopIteration = 0;
754 /* Do a first pass to obtain iterators for the arguments, and set len
755 * to the largest of their lengths.
757 len = 0;
758 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
759 PyObject *curseq;
760 int curlen;
762 /* Get iterator. */
763 curseq = PyTuple_GetItem(args, i+1);
764 sqp->it = PyObject_GetIter(curseq);
765 if (sqp->it == NULL) {
766 static char errmsg[] =
767 "argument %d to map() must support iteration";
768 char errbuf[sizeof(errmsg) + 25];
769 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
770 PyErr_SetString(PyExc_TypeError, errbuf);
771 goto Fail_2;
774 /* Update len. */
775 curlen = -1; /* unknown */
776 if (PySequence_Check(curseq) &&
777 curseq->ob_type->tp_as_sequence->sq_length) {
778 curlen = PySequence_Size(curseq);
779 if (curlen < 0)
780 PyErr_Clear();
782 if (curlen < 0)
783 curlen = 8; /* arbitrary */
784 if (curlen > len)
785 len = curlen;
788 /* Get space for the result list. */
789 if ((result = (PyObject *) PyList_New(len)) == NULL)
790 goto Fail_2;
792 /* Iterate over the sequences until all have stopped. */
793 for (i = 0; ; ++i) {
794 PyObject *alist, *item=NULL, *value;
795 int numactive = 0;
797 if (func == Py_None && n == 1)
798 alist = NULL;
799 else if ((alist = PyTuple_New(n)) == NULL)
800 goto Fail_1;
802 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
803 if (sqp->saw_StopIteration) {
804 Py_INCREF(Py_None);
805 item = Py_None;
807 else {
808 item = PyIter_Next(sqp->it);
809 if (item)
810 ++numactive;
811 else {
812 if (PyErr_Occurred()) {
813 Py_XDECREF(alist);
814 goto Fail_1;
816 Py_INCREF(Py_None);
817 item = Py_None;
818 sqp->saw_StopIteration = 1;
821 if (alist)
822 PyTuple_SET_ITEM(alist, j, item);
823 else
824 break;
827 if (!alist)
828 alist = item;
830 if (numactive == 0) {
831 Py_DECREF(alist);
832 break;
835 if (func == Py_None)
836 value = alist;
837 else {
838 value = PyEval_CallObject(func, alist);
839 Py_DECREF(alist);
840 if (value == NULL)
841 goto Fail_1;
843 if (i >= len) {
844 int status = PyList_Append(result, value);
845 Py_DECREF(value);
846 if (status < 0)
847 goto Fail_1;
849 else if (PyList_SetItem(result, i, value) < 0)
850 goto Fail_1;
853 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
854 goto Fail_1;
856 goto Succeed;
858 Fail_1:
859 Py_DECREF(result);
860 Fail_2:
861 result = NULL;
862 Succeed:
863 assert(seqs);
864 for (i = 0; i < n; ++i)
865 Py_XDECREF(seqs[i].it);
866 PyMem_DEL(seqs);
867 return result;
870 PyDoc_STRVAR(map_doc,
871 "map(function, sequence[, sequence, ...]) -> list\n\
873 Return a list of the results of applying the function to the items of\n\
874 the argument sequence(s). If more than one sequence is given, the\n\
875 function is called with an argument list consisting of the corresponding\n\
876 item of each sequence, substituting None for missing values when not all\n\
877 sequences have the same length. If the function is None, return a list of\n\
878 the items of the sequence (or a list of tuples if more than one sequence).");
881 static PyObject *
882 builtin_setattr(PyObject *self, PyObject *args)
884 PyObject *v;
885 PyObject *name;
886 PyObject *value;
888 if (!PyArg_ParseTuple(args, "OOO:setattr", &v, &name, &value))
889 return NULL;
890 if (PyObject_SetAttr(v, name, value) != 0)
891 return NULL;
892 Py_INCREF(Py_None);
893 return Py_None;
896 PyDoc_STRVAR(setattr_doc,
897 "setattr(object, name, value)\n\
899 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
900 ``x.y = v''.");
903 static PyObject *
904 builtin_delattr(PyObject *self, PyObject *args)
906 PyObject *v;
907 PyObject *name;
909 if (!PyArg_ParseTuple(args, "OO:delattr", &v, &name))
910 return NULL;
911 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
912 return NULL;
913 Py_INCREF(Py_None);
914 return Py_None;
917 PyDoc_STRVAR(delattr_doc,
918 "delattr(object, name)\n\
920 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
921 ``del x.y''.");
924 static PyObject *
925 builtin_hash(PyObject *self, PyObject *v)
927 long x;
929 x = PyObject_Hash(v);
930 if (x == -1)
931 return NULL;
932 return PyInt_FromLong(x);
935 PyDoc_STRVAR(hash_doc,
936 "hash(object) -> integer\n\
938 Return a hash value for the object. Two objects with the same value have\n\
939 the same hash value. The reverse is not necessarily true, but likely.");
942 static PyObject *
943 builtin_hex(PyObject *self, PyObject *v)
945 PyNumberMethods *nb;
947 if ((nb = v->ob_type->tp_as_number) == NULL ||
948 nb->nb_hex == NULL) {
949 PyErr_SetString(PyExc_TypeError,
950 "hex() argument can't be converted to hex");
951 return NULL;
953 return (*nb->nb_hex)(v);
956 PyDoc_STRVAR(hex_doc,
957 "hex(number) -> string\n\
959 Return the hexadecimal representation of an integer or long integer.");
962 static PyObject *builtin_raw_input(PyObject *, PyObject *);
964 static PyObject *
965 builtin_input(PyObject *self, PyObject *args)
967 PyObject *line;
968 char *str;
969 PyObject *res;
970 PyObject *globals, *locals;
972 line = builtin_raw_input(self, args);
973 if (line == NULL)
974 return line;
975 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
976 return NULL;
977 while (*str == ' ' || *str == '\t')
978 str++;
979 globals = PyEval_GetGlobals();
980 locals = PyEval_GetLocals();
981 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
982 if (PyDict_SetItemString(globals, "__builtins__",
983 PyEval_GetBuiltins()) != 0)
984 return NULL;
986 res = PyRun_String(str, Py_eval_input, globals, locals);
987 Py_DECREF(line);
988 return res;
991 PyDoc_STRVAR(input_doc,
992 "input([prompt]) -> value\n\
994 Equivalent to eval(raw_input(prompt)).");
997 static PyObject *
998 builtin_intern(PyObject *self, PyObject *args)
1000 PyObject *s;
1001 if (!PyArg_ParseTuple(args, "S:intern", &s))
1002 return NULL;
1003 Py_INCREF(s);
1004 PyString_InternInPlace(&s);
1005 return s;
1008 PyDoc_STRVAR(intern_doc,
1009 "intern(string) -> string\n\
1011 ``Intern'' the given string. This enters the string in the (global)\n\
1012 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1013 Return the string itself or the previously interned string object with the\n\
1014 same value.");
1017 static PyObject *
1018 builtin_iter(PyObject *self, PyObject *args)
1020 PyObject *v, *w = NULL;
1022 if (!PyArg_ParseTuple(args, "O|O:iter", &v, &w))
1023 return NULL;
1024 if (w == NULL)
1025 return PyObject_GetIter(v);
1026 if (!PyCallable_Check(v)) {
1027 PyErr_SetString(PyExc_TypeError,
1028 "iter(v, w): v must be callable");
1029 return NULL;
1031 return PyCallIter_New(v, w);
1034 PyDoc_STRVAR(iter_doc,
1035 "iter(collection) -> iterator\n\
1036 iter(callable, sentinel) -> iterator\n\
1038 Get an iterator from an object. In the first form, the argument must\n\
1039 supply its own iterator, or be a sequence.\n\
1040 In the second form, the callable is called until it returns the sentinel.");
1043 static PyObject *
1044 builtin_len(PyObject *self, PyObject *v)
1046 long res;
1048 res = PyObject_Size(v);
1049 if (res < 0 && PyErr_Occurred())
1050 return NULL;
1051 return PyInt_FromLong(res);
1054 PyDoc_STRVAR(len_doc,
1055 "len(object) -> integer\n\
1057 Return the number of items of a sequence or mapping.");
1060 static PyObject *
1061 builtin_locals(PyObject *self)
1063 PyObject *d;
1065 d = PyEval_GetLocals();
1066 Py_INCREF(d);
1067 return d;
1070 PyDoc_STRVAR(locals_doc,
1071 "locals() -> dictionary\n\
1073 Return the dictionary containing the current scope's local variables.");
1076 static PyObject *
1077 min_max(PyObject *args, int op)
1079 PyObject *v, *w, *x, *it;
1081 if (PyTuple_Size(args) > 1)
1082 v = args;
1083 else if (!PyArg_ParseTuple(args, "O:min/max", &v))
1084 return NULL;
1086 it = PyObject_GetIter(v);
1087 if (it == NULL)
1088 return NULL;
1090 w = NULL; /* the result */
1091 for (;;) {
1092 x = PyIter_Next(it);
1093 if (x == NULL) {
1094 if (PyErr_Occurred()) {
1095 Py_XDECREF(w);
1096 Py_DECREF(it);
1097 return NULL;
1099 break;
1102 if (w == NULL)
1103 w = x;
1104 else {
1105 int cmp = PyObject_RichCompareBool(x, w, op);
1106 if (cmp > 0) {
1107 Py_DECREF(w);
1108 w = x;
1110 else if (cmp < 0) {
1111 Py_DECREF(x);
1112 Py_DECREF(w);
1113 Py_DECREF(it);
1114 return NULL;
1116 else
1117 Py_DECREF(x);
1120 if (w == NULL)
1121 PyErr_SetString(PyExc_ValueError,
1122 "min() or max() arg is an empty sequence");
1123 Py_DECREF(it);
1124 return w;
1127 static PyObject *
1128 builtin_min(PyObject *self, PyObject *v)
1130 return min_max(v, Py_LT);
1133 PyDoc_STRVAR(min_doc,
1134 "min(sequence) -> value\n\
1135 min(a, b, c, ...) -> value\n\
1137 With a single sequence argument, return its smallest item.\n\
1138 With two or more arguments, return the smallest argument.");
1141 static PyObject *
1142 builtin_max(PyObject *self, PyObject *v)
1144 return min_max(v, Py_GT);
1147 PyDoc_STRVAR(max_doc,
1148 "max(sequence) -> value\n\
1149 max(a, b, c, ...) -> value\n\
1151 With a single sequence argument, return its largest item.\n\
1152 With two or more arguments, return the largest argument.");
1155 static PyObject *
1156 builtin_oct(PyObject *self, PyObject *v)
1158 PyNumberMethods *nb;
1160 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1161 nb->nb_oct == NULL) {
1162 PyErr_SetString(PyExc_TypeError,
1163 "oct() argument can't be converted to oct");
1164 return NULL;
1166 return (*nb->nb_oct)(v);
1169 PyDoc_STRVAR(oct_doc,
1170 "oct(number) -> string\n\
1172 Return the octal representation of an integer or long integer.");
1175 static PyObject *
1176 builtin_ord(PyObject *self, PyObject* obj)
1178 long ord;
1179 int size;
1181 if (PyString_Check(obj)) {
1182 size = PyString_GET_SIZE(obj);
1183 if (size == 1) {
1184 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1185 return PyInt_FromLong(ord);
1187 #ifdef Py_USING_UNICODE
1188 } else if (PyUnicode_Check(obj)) {
1189 size = PyUnicode_GET_SIZE(obj);
1190 if (size == 1) {
1191 ord = (long)*PyUnicode_AS_UNICODE(obj);
1192 return PyInt_FromLong(ord);
1194 #endif
1195 } else {
1196 PyErr_Format(PyExc_TypeError,
1197 "ord() expected string of length 1, but " \
1198 "%.200s found", obj->ob_type->tp_name);
1199 return NULL;
1202 PyErr_Format(PyExc_TypeError,
1203 "ord() expected a character, "
1204 "but string of length %d found",
1205 size);
1206 return NULL;
1209 PyDoc_STRVAR(ord_doc,
1210 "ord(c) -> integer\n\
1212 Return the integer ordinal of a one-character string.");
1215 static PyObject *
1216 builtin_pow(PyObject *self, PyObject *args)
1218 PyObject *v, *w, *z = Py_None;
1220 if (!PyArg_ParseTuple(args, "OO|O:pow", &v, &w, &z))
1221 return NULL;
1222 return PyNumber_Power(v, w, z);
1225 PyDoc_STRVAR(pow_doc,
1226 "pow(x, y[, z]) -> number\n\
1228 With two arguments, equivalent to x**y. With three arguments,\n\
1229 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1232 /* Return number of items in range/xrange (lo, hi, step). step > 0
1233 * required. Return a value < 0 if & only if the true value is too
1234 * large to fit in a signed long.
1236 static long
1237 get_len_of_range(long lo, long hi, long step)
1239 /* -------------------------------------------------------------
1240 If lo >= hi, the range is empty.
1241 Else if n values are in the range, the last one is
1242 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1243 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1244 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1245 the RHS is non-negative and so truncation is the same as the
1246 floor. Letting M be the largest positive long, the worst case
1247 for the RHS numerator is hi=M, lo=-M-1, and then
1248 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1249 precision to compute the RHS exactly.
1250 ---------------------------------------------------------------*/
1251 long n = 0;
1252 if (lo < hi) {
1253 unsigned long uhi = (unsigned long)hi;
1254 unsigned long ulo = (unsigned long)lo;
1255 unsigned long diff = uhi - ulo - 1;
1256 n = (long)(diff / (unsigned long)step + 1);
1258 return n;
1261 static PyObject *
1262 builtin_range(PyObject *self, PyObject *args)
1264 long ilow = 0, ihigh = 0, istep = 1;
1265 long bign;
1266 int i, n;
1268 PyObject *v;
1270 if (PyTuple_Size(args) <= 1) {
1271 if (!PyArg_ParseTuple(args,
1272 "l;range() requires 1-3 int arguments",
1273 &ihigh))
1274 return NULL;
1276 else {
1277 if (!PyArg_ParseTuple(args,
1278 "ll|l;range() requires 1-3 int arguments",
1279 &ilow, &ihigh, &istep))
1280 return NULL;
1282 if (istep == 0) {
1283 PyErr_SetString(PyExc_ValueError, "range() arg 3 must not be zero");
1284 return NULL;
1286 if (istep > 0)
1287 bign = get_len_of_range(ilow, ihigh, istep);
1288 else
1289 bign = get_len_of_range(ihigh, ilow, -istep);
1290 n = (int)bign;
1291 if (bign < 0 || (long)n != bign) {
1292 PyErr_SetString(PyExc_OverflowError,
1293 "range() result has too many items");
1294 return NULL;
1296 v = PyList_New(n);
1297 if (v == NULL)
1298 return NULL;
1299 for (i = 0; i < n; i++) {
1300 PyObject *w = PyInt_FromLong(ilow);
1301 if (w == NULL) {
1302 Py_DECREF(v);
1303 return NULL;
1305 PyList_SET_ITEM(v, i, w);
1306 ilow += istep;
1308 return v;
1311 PyDoc_STRVAR(range_doc,
1312 "range([start,] stop[, step]) -> list of integers\n\
1314 Return a list containing an arithmetic progression of integers.\n\
1315 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1316 When step is given, it specifies the increment (or decrement).\n\
1317 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1318 These are exactly the valid indices for a list of 4 elements.");
1321 static PyObject *
1322 builtin_raw_input(PyObject *self, PyObject *args)
1324 PyObject *v = NULL;
1325 PyObject *f;
1327 if (!PyArg_ParseTuple(args, "|O:[raw_]input", &v))
1328 return NULL;
1329 if (PyFile_AsFile(PySys_GetObject("stdin")) == stdin &&
1330 PyFile_AsFile(PySys_GetObject("stdout")) == stdout &&
1331 isatty(fileno(stdin)) && isatty(fileno(stdout))) {
1332 PyObject *po;
1333 char *prompt;
1334 char *s;
1335 PyObject *result;
1336 if (v != NULL) {
1337 po = PyObject_Str(v);
1338 if (po == NULL)
1339 return NULL;
1340 prompt = PyString_AsString(po);
1341 if (prompt == NULL)
1342 return NULL;
1344 else {
1345 po = NULL;
1346 prompt = "";
1348 s = PyOS_Readline(prompt);
1349 Py_XDECREF(po);
1350 if (s == NULL) {
1351 PyErr_SetNone(PyExc_KeyboardInterrupt);
1352 return NULL;
1354 if (*s == '\0') {
1355 PyErr_SetNone(PyExc_EOFError);
1356 result = NULL;
1358 else { /* strip trailing '\n' */
1359 size_t len = strlen(s);
1360 if (len > INT_MAX) {
1361 PyErr_SetString(PyExc_OverflowError, "input too long");
1362 result = NULL;
1364 else {
1365 result = PyString_FromStringAndSize(s, (int)(len-1));
1368 PyMem_FREE(s);
1369 return result;
1371 if (v != NULL) {
1372 f = PySys_GetObject("stdout");
1373 if (f == NULL) {
1374 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1375 return NULL;
1377 if (Py_FlushLine() != 0 ||
1378 PyFile_WriteObject(v, f, Py_PRINT_RAW) != 0)
1379 return NULL;
1381 f = PySys_GetObject("stdin");
1382 if (f == NULL) {
1383 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdin");
1384 return NULL;
1386 return PyFile_GetLine(f, -1);
1389 PyDoc_STRVAR(raw_input_doc,
1390 "raw_input([prompt]) -> string\n\
1392 Read a string from standard input. The trailing newline is stripped.\n\
1393 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1394 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1395 is printed without a trailing newline before reading.");
1398 static PyObject *
1399 builtin_reduce(PyObject *self, PyObject *args)
1401 PyObject *seq, *func, *result = NULL, *it;
1403 if (!PyArg_ParseTuple(args, "OO|O:reduce", &func, &seq, &result))
1404 return NULL;
1405 if (result != NULL)
1406 Py_INCREF(result);
1408 it = PyObject_GetIter(seq);
1409 if (it == NULL) {
1410 PyErr_SetString(PyExc_TypeError,
1411 "reduce() arg 2 must support iteration");
1412 Py_XDECREF(result);
1413 return NULL;
1416 if ((args = PyTuple_New(2)) == NULL)
1417 goto Fail;
1419 for (;;) {
1420 PyObject *op2;
1422 if (args->ob_refcnt > 1) {
1423 Py_DECREF(args);
1424 if ((args = PyTuple_New(2)) == NULL)
1425 goto Fail;
1428 op2 = PyIter_Next(it);
1429 if (op2 == NULL) {
1430 if (PyErr_Occurred())
1431 goto Fail;
1432 break;
1435 if (result == NULL)
1436 result = op2;
1437 else {
1438 PyTuple_SetItem(args, 0, result);
1439 PyTuple_SetItem(args, 1, op2);
1440 if ((result = PyEval_CallObject(func, args)) == NULL)
1441 goto Fail;
1445 Py_DECREF(args);
1447 if (result == NULL)
1448 PyErr_SetString(PyExc_TypeError,
1449 "reduce() of empty sequence with no initial value");
1451 Py_DECREF(it);
1452 return result;
1454 Fail:
1455 Py_XDECREF(args);
1456 Py_XDECREF(result);
1457 Py_DECREF(it);
1458 return NULL;
1461 PyDoc_STRVAR(reduce_doc,
1462 "reduce(function, sequence[, initial]) -> value\n\
1464 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1465 from left to right, so as to reduce the sequence to a single value.\n\
1466 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1467 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1468 of the sequence in the calculation, and serves as a default when the\n\
1469 sequence is empty.");
1472 static PyObject *
1473 builtin_reload(PyObject *self, PyObject *v)
1475 return PyImport_ReloadModule(v);
1478 PyDoc_STRVAR(reload_doc,
1479 "reload(module) -> module\n\
1481 Reload the module. The module must have been successfully imported before.");
1484 static PyObject *
1485 builtin_repr(PyObject *self, PyObject *v)
1487 return PyObject_Repr(v);
1490 PyDoc_STRVAR(repr_doc,
1491 "repr(object) -> string\n\
1493 Return the canonical string representation of the object.\n\
1494 For most object types, eval(repr(object)) == object.");
1497 static PyObject *
1498 builtin_round(PyObject *self, PyObject *args)
1500 double x;
1501 double f;
1502 int ndigits = 0;
1503 int i;
1505 if (!PyArg_ParseTuple(args, "d|i:round", &x, &ndigits))
1506 return NULL;
1507 f = 1.0;
1508 i = abs(ndigits);
1509 while (--i >= 0)
1510 f = f*10.0;
1511 if (ndigits < 0)
1512 x /= f;
1513 else
1514 x *= f;
1515 if (x >= 0.0)
1516 x = floor(x + 0.5);
1517 else
1518 x = ceil(x - 0.5);
1519 if (ndigits < 0)
1520 x *= f;
1521 else
1522 x /= f;
1523 return PyFloat_FromDouble(x);
1526 PyDoc_STRVAR(round_doc,
1527 "round(number[, ndigits]) -> floating point number\n\
1529 Round a number to a given precision in decimal digits (default 0 digits).\n\
1530 This always returns a floating point number. Precision may be negative.");
1533 static PyObject *
1534 builtin_vars(PyObject *self, PyObject *args)
1536 PyObject *v = NULL;
1537 PyObject *d;
1539 if (!PyArg_ParseTuple(args, "|O:vars", &v))
1540 return NULL;
1541 if (v == NULL) {
1542 d = PyEval_GetLocals();
1543 if (d == NULL) {
1544 if (!PyErr_Occurred())
1545 PyErr_SetString(PyExc_SystemError,
1546 "no locals!?");
1548 else
1549 Py_INCREF(d);
1551 else {
1552 d = PyObject_GetAttrString(v, "__dict__");
1553 if (d == NULL) {
1554 PyErr_SetString(PyExc_TypeError,
1555 "vars() argument must have __dict__ attribute");
1556 return NULL;
1559 return d;
1562 PyDoc_STRVAR(vars_doc,
1563 "vars([object]) -> dictionary\n\
1565 Without arguments, equivalent to locals().\n\
1566 With an argument, equivalent to object.__dict__.");
1568 static PyObject *
1569 builtin_isinstance(PyObject *self, PyObject *args)
1571 PyObject *inst;
1572 PyObject *cls;
1573 int retval;
1575 if (!PyArg_ParseTuple(args, "OO:isinstance", &inst, &cls))
1576 return NULL;
1578 retval = PyObject_IsInstance(inst, cls);
1579 if (retval < 0)
1580 return NULL;
1581 return PyBool_FromLong(retval);
1584 PyDoc_STRVAR(isinstance_doc,
1585 "isinstance(object, class-or-type-or-tuple) -> bool\n\
1587 Return whether an object is an instance of a class or of a subclass thereof.\n\
1588 With a type as second argument, return whether that is the object's type.\n\
1589 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
1590 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
1593 static PyObject *
1594 builtin_issubclass(PyObject *self, PyObject *args)
1596 PyObject *derived;
1597 PyObject *cls;
1598 int retval;
1600 if (!PyArg_ParseTuple(args, "OO:issubclass", &derived, &cls))
1601 return NULL;
1603 retval = PyObject_IsSubclass(derived, cls);
1604 if (retval < 0)
1605 return NULL;
1606 return PyBool_FromLong(retval);
1609 PyDoc_STRVAR(issubclass_doc,
1610 "issubclass(C, B) -> bool\n\
1612 Return whether class C is a subclass (i.e., a derived class) of class B.");
1615 static PyObject*
1616 builtin_zip(PyObject *self, PyObject *args)
1618 PyObject *ret;
1619 const int itemsize = PySequence_Length(args);
1620 int i;
1621 PyObject *itlist; /* tuple of iterators */
1622 int len; /* guess at result length */
1624 if (itemsize < 1) {
1625 PyErr_SetString(PyExc_TypeError,
1626 "zip() requires at least one sequence");
1627 return NULL;
1629 /* args must be a tuple */
1630 assert(PyTuple_Check(args));
1632 /* Guess at result length: the shortest of the input lengths.
1633 If some argument refuses to say, we refuse to guess too, lest
1634 an argument like xrange(sys.maxint) lead us astray.*/
1635 len = -1; /* unknown */
1636 for (i = 0; i < itemsize; ++i) {
1637 PyObject *item = PyTuple_GET_ITEM(args, i);
1638 int thislen = PySequence_Length(item);
1639 if (thislen < 0) {
1640 PyErr_Clear();
1641 len = -1;
1642 break;
1644 else if (len < 0 || thislen < len)
1645 len = thislen;
1648 /* allocate result list */
1649 if (len < 0)
1650 len = 10; /* arbitrary */
1651 if ((ret = PyList_New(len)) == NULL)
1652 return NULL;
1654 /* obtain iterators */
1655 itlist = PyTuple_New(itemsize);
1656 if (itlist == NULL)
1657 goto Fail_ret;
1658 for (i = 0; i < itemsize; ++i) {
1659 PyObject *item = PyTuple_GET_ITEM(args, i);
1660 PyObject *it = PyObject_GetIter(item);
1661 if (it == NULL) {
1662 if (PyErr_ExceptionMatches(PyExc_TypeError))
1663 PyErr_Format(PyExc_TypeError,
1664 "zip argument #%d must support iteration",
1665 i+1);
1666 goto Fail_ret_itlist;
1668 PyTuple_SET_ITEM(itlist, i, it);
1671 /* build result into ret list */
1672 for (i = 0; ; ++i) {
1673 int j;
1674 PyObject *next = PyTuple_New(itemsize);
1675 if (!next)
1676 goto Fail_ret_itlist;
1678 for (j = 0; j < itemsize; j++) {
1679 PyObject *it = PyTuple_GET_ITEM(itlist, j);
1680 PyObject *item = PyIter_Next(it);
1681 if (!item) {
1682 if (PyErr_Occurred()) {
1683 Py_DECREF(ret);
1684 ret = NULL;
1686 Py_DECREF(next);
1687 Py_DECREF(itlist);
1688 goto Done;
1690 PyTuple_SET_ITEM(next, j, item);
1693 if (i < len)
1694 PyList_SET_ITEM(ret, i, next);
1695 else {
1696 int status = PyList_Append(ret, next);
1697 Py_DECREF(next);
1698 ++len;
1699 if (status < 0)
1700 goto Fail_ret_itlist;
1704 Done:
1705 if (ret != NULL && i < len) {
1706 /* The list is too big. */
1707 if (PyList_SetSlice(ret, i, len, NULL) < 0)
1708 return NULL;
1710 return ret;
1712 Fail_ret_itlist:
1713 Py_DECREF(itlist);
1714 Fail_ret:
1715 Py_DECREF(ret);
1716 return NULL;
1720 PyDoc_STRVAR(zip_doc,
1721 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
1723 Return a list of tuples, where each tuple contains the i-th element\n\
1724 from each of the argument sequences. The returned list is truncated\n\
1725 in length to the length of the shortest argument sequence.");
1728 static PyMethodDef builtin_methods[] = {
1729 {"__import__", builtin___import__, METH_VARARGS, import_doc},
1730 {"abs", builtin_abs, METH_O, abs_doc},
1731 {"apply", builtin_apply, METH_VARARGS, apply_doc},
1732 {"callable", builtin_callable, METH_O, callable_doc},
1733 {"chr", builtin_chr, METH_VARARGS, chr_doc},
1734 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
1735 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
1736 {"compile", builtin_compile, METH_VARARGS, compile_doc},
1737 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
1738 {"dir", builtin_dir, METH_VARARGS, dir_doc},
1739 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
1740 {"eval", builtin_eval, METH_VARARGS, eval_doc},
1741 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
1742 {"filter", builtin_filter, METH_VARARGS, filter_doc},
1743 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
1744 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
1745 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
1746 {"hash", builtin_hash, METH_O, hash_doc},
1747 {"hex", builtin_hex, METH_O, hex_doc},
1748 {"id", builtin_id, METH_O, id_doc},
1749 {"input", builtin_input, METH_VARARGS, input_doc},
1750 {"intern", builtin_intern, METH_VARARGS, intern_doc},
1751 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
1752 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
1753 {"iter", builtin_iter, METH_VARARGS, iter_doc},
1754 {"len", builtin_len, METH_O, len_doc},
1755 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
1756 {"map", builtin_map, METH_VARARGS, map_doc},
1757 {"max", builtin_max, METH_VARARGS, max_doc},
1758 {"min", builtin_min, METH_VARARGS, min_doc},
1759 {"oct", builtin_oct, METH_O, oct_doc},
1760 {"ord", builtin_ord, METH_O, ord_doc},
1761 {"pow", builtin_pow, METH_VARARGS, pow_doc},
1762 {"range", builtin_range, METH_VARARGS, range_doc},
1763 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
1764 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
1765 {"reload", builtin_reload, METH_O, reload_doc},
1766 {"repr", builtin_repr, METH_O, repr_doc},
1767 {"round", builtin_round, METH_VARARGS, round_doc},
1768 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
1769 #ifdef Py_USING_UNICODE
1770 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
1771 #endif
1772 {"vars", builtin_vars, METH_VARARGS, vars_doc},
1773 {"zip", builtin_zip, METH_VARARGS, zip_doc},
1774 {NULL, NULL},
1777 PyDoc_STRVAR(builtin_doc,
1778 "Built-in functions, exceptions, and other objects.\n\
1780 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
1782 PyObject *
1783 _PyBuiltin_Init(void)
1785 PyObject *mod, *dict, *debug;
1786 mod = Py_InitModule4("__builtin__", builtin_methods,
1787 builtin_doc, (PyObject *)NULL,
1788 PYTHON_API_VERSION);
1789 if (mod == NULL)
1790 return NULL;
1791 dict = PyModule_GetDict(mod);
1793 #define SETBUILTIN(NAME, OBJECT) \
1794 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
1795 return NULL
1797 SETBUILTIN("None", Py_None);
1798 SETBUILTIN("Ellipsis", Py_Ellipsis);
1799 SETBUILTIN("NotImplemented", Py_NotImplemented);
1800 SETBUILTIN("False", Py_False);
1801 SETBUILTIN("True", Py_True);
1802 SETBUILTIN("basestring", &PyBaseString_Type);
1803 SETBUILTIN("bool", &PyBool_Type);
1804 SETBUILTIN("buffer", &PyBuffer_Type);
1805 SETBUILTIN("classmethod", &PyClassMethod_Type);
1806 #ifndef WITHOUT_COMPLEX
1807 SETBUILTIN("complex", &PyComplex_Type);
1808 #endif
1809 SETBUILTIN("dict", &PyDict_Type);
1810 SETBUILTIN("enumerate", &PyEnum_Type);
1811 SETBUILTIN("float", &PyFloat_Type);
1812 SETBUILTIN("property", &PyProperty_Type);
1813 SETBUILTIN("int", &PyInt_Type);
1814 SETBUILTIN("list", &PyList_Type);
1815 SETBUILTIN("long", &PyLong_Type);
1816 SETBUILTIN("object", &PyBaseObject_Type);
1817 SETBUILTIN("slice", &PySlice_Type);
1818 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
1819 SETBUILTIN("str", &PyString_Type);
1820 SETBUILTIN("super", &PySuper_Type);
1821 SETBUILTIN("tuple", &PyTuple_Type);
1822 SETBUILTIN("type", &PyType_Type);
1823 SETBUILTIN("xrange", &PyRange_Type);
1825 /* Note that open() is just an alias of file(). */
1826 SETBUILTIN("open", &PyFile_Type);
1827 SETBUILTIN("file", &PyFile_Type);
1828 #ifdef Py_USING_UNICODE
1829 SETBUILTIN("unicode", &PyUnicode_Type);
1830 #endif
1831 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
1832 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
1833 Py_XDECREF(debug);
1834 return NULL;
1836 Py_XDECREF(debug);
1838 return mod;
1839 #undef SETBUILTIN
1842 /* Helper for filter(): filter a tuple through a function */
1844 static PyObject *
1845 filtertuple(PyObject *func, PyObject *tuple)
1847 PyObject *result;
1848 register int i, j;
1849 int len = PyTuple_Size(tuple);
1851 if (len == 0) {
1852 Py_INCREF(tuple);
1853 return tuple;
1856 if ((result = PyTuple_New(len)) == NULL)
1857 return NULL;
1859 for (i = j = 0; i < len; ++i) {
1860 PyObject *item, *good;
1861 int ok;
1863 if ((item = PyTuple_GetItem(tuple, i)) == NULL)
1864 goto Fail_1;
1865 if (func == Py_None) {
1866 Py_INCREF(item);
1867 good = item;
1869 else {
1870 PyObject *arg = Py_BuildValue("(O)", item);
1871 if (arg == NULL)
1872 goto Fail_1;
1873 good = PyEval_CallObject(func, arg);
1874 Py_DECREF(arg);
1875 if (good == NULL)
1876 goto Fail_1;
1878 ok = PyObject_IsTrue(good);
1879 Py_DECREF(good);
1880 if (ok) {
1881 Py_INCREF(item);
1882 if (PyTuple_SetItem(result, j++, item) < 0)
1883 goto Fail_1;
1887 if (_PyTuple_Resize(&result, j) < 0)
1888 return NULL;
1890 return result;
1892 Fail_1:
1893 Py_DECREF(result);
1894 return NULL;
1898 /* Helper for filter(): filter a string through a function */
1900 static PyObject *
1901 filterstring(PyObject *func, PyObject *strobj)
1903 PyObject *result;
1904 register int i, j;
1905 int len = PyString_Size(strobj);
1907 if (func == Py_None) {
1908 /* No character is ever false -- share input string */
1909 Py_INCREF(strobj);
1910 return strobj;
1912 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
1913 return NULL;
1915 for (i = j = 0; i < len; ++i) {
1916 PyObject *item, *arg, *good;
1917 int ok;
1919 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
1920 if (item == NULL)
1921 goto Fail_1;
1922 arg = Py_BuildValue("(O)", item);
1923 if (arg == NULL) {
1924 Py_DECREF(item);
1925 goto Fail_1;
1927 good = PyEval_CallObject(func, arg);
1928 Py_DECREF(arg);
1929 if (good == NULL) {
1930 Py_DECREF(item);
1931 goto Fail_1;
1933 ok = PyObject_IsTrue(good);
1934 Py_DECREF(good);
1935 if (ok)
1936 PyString_AS_STRING((PyStringObject *)result)[j++] =
1937 PyString_AS_STRING((PyStringObject *)item)[0];
1938 Py_DECREF(item);
1941 if (j < len)
1942 _PyString_Resize(&result, j);
1944 return result;
1946 Fail_1:
1947 Py_DECREF(result);
1948 return NULL;