Merged release21-maint changes.
[python/dscho.git] / Python / bltinmodule.c
blobfa6816279dfd5d3052bf4a5d5dd629eddadbc7d1
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 /* 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 static char 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 *args)
58 PyObject *v;
60 if (!PyArg_ParseTuple(args, "O:abs", &v))
61 return NULL;
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 *args)
137 PyObject *v;
139 if (!PyArg_ParseTuple(args, "O:callable", &v))
140 return NULL;
141 return PyInt_FromLong((long)PyCallable_Check(v));
144 static char callable_doc[] =
145 "callable(object) -> Boolean\n\
147 Return whether the object is callable (i.e., some kind of function).\n\
148 Note that classes are callable, as are instances with a __call__() method.";
151 static PyObject *
152 builtin_filter(PyObject *self, PyObject *args)
154 PyObject *func, *seq, *result, *it;
155 int len; /* guess for result list size */
156 register int j;
158 if (!PyArg_ParseTuple(args, "OO:filter", &func, &seq))
159 return NULL;
161 /* Strings and tuples return a result of the same type. */
162 if (PyString_Check(seq))
163 return filterstring(func, seq);
164 if (PyTuple_Check(seq))
165 return filtertuple(func, seq);
167 /* Get iterator. */
168 it = PyObject_GetIter(seq);
169 if (it == NULL)
170 return NULL;
172 /* Guess a result list size. */
173 len = -1; /* unknown */
174 if (PySequence_Check(seq) &&
175 seq->ob_type->tp_as_sequence->sq_length) {
176 len = PySequence_Size(seq);
177 if (len < 0)
178 PyErr_Clear();
180 if (len < 0)
181 len = 8; /* arbitrary */
183 /* Get a result list. */
184 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
185 /* Eww - can modify the list in-place. */
186 Py_INCREF(seq);
187 result = seq;
189 else {
190 result = PyList_New(len);
191 if (result == NULL)
192 goto Fail_it;
195 /* Build the result list. */
196 j = 0;
197 for (;;) {
198 PyObject *item, *good;
199 int ok;
201 item = PyIter_Next(it);
202 if (item == NULL) {
203 if (PyErr_Occurred())
204 goto Fail_result_it;
205 break;
208 if (func == Py_None) {
209 good = item;
210 Py_INCREF(good);
212 else {
213 PyObject *arg = Py_BuildValue("(O)", item);
214 if (arg == NULL) {
215 Py_DECREF(item);
216 goto Fail_result_it;
218 good = PyEval_CallObject(func, arg);
219 Py_DECREF(arg);
220 if (good == NULL) {
221 Py_DECREF(item);
222 goto Fail_result_it;
225 ok = PyObject_IsTrue(good);
226 Py_DECREF(good);
227 if (ok) {
228 if (j < len)
229 PyList_SET_ITEM(result, j, item);
230 else {
231 int status = PyList_Append(result, item);
232 Py_DECREF(item);
233 if (status < 0)
234 goto Fail_result_it;
236 ++j;
238 else
239 Py_DECREF(item);
243 /* Cut back result list if len is too big. */
244 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
245 goto Fail_result_it;
247 Py_DECREF(it);
248 return result;
250 Fail_result_it:
251 Py_DECREF(result);
252 Fail_it:
253 Py_DECREF(it);
254 return NULL;
257 static char filter_doc[] =
258 "filter(function, sequence) -> list\n\
260 Return a list containing those items of sequence for which function(item)\n\
261 is true. If function is None, return a list of items that are true.";
264 static PyObject *
265 builtin_chr(PyObject *self, PyObject *args)
267 long x;
268 char s[1];
270 if (!PyArg_ParseTuple(args, "l:chr", &x))
271 return NULL;
272 if (x < 0 || x >= 256) {
273 PyErr_SetString(PyExc_ValueError,
274 "chr() arg not in range(256)");
275 return NULL;
277 s[0] = (char)x;
278 return PyString_FromStringAndSize(s, 1);
281 static char chr_doc[] =
282 "chr(i) -> character\n\
284 Return a string of one character with ordinal i; 0 <= i < 256.";
287 static PyObject *
288 builtin_unichr(PyObject *self, PyObject *args)
290 long x;
291 Py_UNICODE s[2];
293 if (!PyArg_ParseTuple(args, "l:unichr", &x))
294 return NULL;
296 #ifdef Py_UNICODE_WIDE
297 if (x < 0 || x > 0x10ffff) {
298 PyErr_SetString(PyExc_ValueError,
299 "unichr() arg not in range(0x110000) "
300 "(wide Python build)");
301 return NULL;
303 #else
304 if (x < 0 || x > 0xffff) {
305 PyErr_SetString(PyExc_ValueError,
306 "unichr() arg not in range(0x10000) "
307 "(narrow Python build)");
308 return NULL;
310 #endif
312 if (x <= 0xffff) {
313 /* UCS-2 character */
314 s[0] = (Py_UNICODE) x;
315 return PyUnicode_FromUnicode(s, 1);
317 else {
318 #ifndef Py_UNICODE_WIDE
319 /* UCS-4 character. store as two surrogate characters */
320 x -= 0x10000L;
321 s[0] = 0xD800 + (Py_UNICODE) (x >> 10);
322 s[1] = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
323 return PyUnicode_FromUnicode(s, 2);
324 #else
325 s[0] = (Py_UNICODE)x;
326 return PyUnicode_FromUnicode(s, 1);
327 #endif
331 static char unichr_doc[] =
332 "unichr(i) -> Unicode character\n\
334 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.";
337 static PyObject *
338 builtin_cmp(PyObject *self, PyObject *args)
340 PyObject *a, *b;
341 int c;
343 if (!PyArg_ParseTuple(args, "OO:cmp", &a, &b))
344 return NULL;
345 if (PyObject_Cmp(a, b, &c) < 0)
346 return NULL;
347 return PyInt_FromLong((long)c);
350 static char cmp_doc[] =
351 "cmp(x, y) -> integer\n\
353 Return negative if x<y, zero if x==y, positive if x>y.";
356 static PyObject *
357 builtin_coerce(PyObject *self, PyObject *args)
359 PyObject *v, *w;
360 PyObject *res;
362 if (!PyArg_ParseTuple(args, "OO:coerce", &v, &w))
363 return NULL;
364 if (PyNumber_Coerce(&v, &w) < 0)
365 return NULL;
366 res = Py_BuildValue("(OO)", v, w);
367 Py_DECREF(v);
368 Py_DECREF(w);
369 return res;
372 static char coerce_doc[] =
373 "coerce(x, y) -> None or (x1, y1)\n\
375 When x and y can be coerced to values of the same type, return a tuple\n\
376 containing the coerced values. When they can't be coerced, return None.";
379 static PyObject *
380 builtin_compile(PyObject *self, PyObject *args)
382 char *str;
383 char *filename;
384 char *startstr;
385 int start;
386 PyCompilerFlags cf;
388 if (!PyArg_ParseTuple(args, "sss:compile", &str, &filename, &startstr))
389 return NULL;
390 if (strcmp(startstr, "exec") == 0)
391 start = Py_file_input;
392 else if (strcmp(startstr, "eval") == 0)
393 start = Py_eval_input;
394 else if (strcmp(startstr, "single") == 0)
395 start = Py_single_input;
396 else {
397 PyErr_SetString(PyExc_ValueError,
398 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
399 return NULL;
401 cf.cf_flags = 0;
402 if (PyEval_MergeCompilerFlags(&cf))
403 return Py_CompileStringFlags(str, filename, start, &cf);
404 else
405 return Py_CompileString(str, filename, start);
408 static char compile_doc[] =
409 "compile(source, filename, mode) -> code object\n\
411 Compile the source string (a Python module, statement or expression)\n\
412 into a code object that can be executed by the exec statement or eval().\n\
413 The filename will be used for run-time error messages.\n\
414 The mode must be 'exec' to compile a module, 'single' to compile a\n\
415 single (interactive) statement, or 'eval' to compile an expression.";
418 static PyObject *
419 builtin_dir(PyObject *self, PyObject *args)
421 static char *attrlist[] = {"__members__", "__methods__", NULL};
422 PyObject *v = NULL, *l = NULL, *m = NULL;
423 PyObject *d, *x;
424 int i;
425 char **s;
427 if (!PyArg_ParseTuple(args, "|O:dir", &v))
428 return NULL;
429 if (v == NULL) {
430 x = PyEval_GetLocals();
431 if (x == NULL)
432 goto error;
433 l = PyMapping_Keys(x);
434 if (l == NULL)
435 goto error;
437 else {
438 d = PyObject_GetAttrString(v, "__dict__");
439 if (d == NULL)
440 PyErr_Clear();
441 else {
442 l = PyMapping_Keys(d);
443 if (l == NULL)
444 PyErr_Clear();
445 Py_DECREF(d);
447 if (l == NULL) {
448 l = PyList_New(0);
449 if (l == NULL)
450 goto error;
452 for (s = attrlist; *s != NULL; s++) {
453 m = PyObject_GetAttrString(v, *s);
454 if (m == NULL) {
455 PyErr_Clear();
456 continue;
458 for (i = 0; ; i++) {
459 x = PySequence_GetItem(m, i);
460 if (x == NULL) {
461 PyErr_Clear();
462 break;
464 if (PyList_Append(l, x) != 0) {
465 Py_DECREF(x);
466 Py_DECREF(m);
467 goto error;
469 Py_DECREF(x);
471 Py_DECREF(m);
474 if (PyList_Sort(l) != 0)
475 goto error;
476 return l;
477 error:
478 Py_XDECREF(l);
479 return NULL;
482 static char dir_doc[] =
483 "dir([object]) -> list of strings\n\
485 Return an alphabetized list of names comprising (some of) the attributes\n\
486 of the given object. Without an argument, the names in the current scope\n\
487 are listed. With an instance argument, only the instance attributes are\n\
488 returned. With a class argument, attributes of the base class are not\n\
489 returned. For other types or arguments, this may list members or methods.";
492 static PyObject *
493 builtin_divmod(PyObject *self, PyObject *args)
495 PyObject *v, *w;
497 if (!PyArg_ParseTuple(args, "OO:divmod", &v, &w))
498 return NULL;
499 return PyNumber_Divmod(v, w);
502 static char divmod_doc[] =
503 "divmod(x, y) -> (div, mod)\n\
505 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.";
508 static PyObject *
509 builtin_eval(PyObject *self, PyObject *args)
511 PyObject *cmd;
512 PyObject *globals = Py_None, *locals = Py_None;
513 char *str;
515 if (!PyArg_ParseTuple(args, "O|O!O!:eval",
516 &cmd,
517 &PyDict_Type, &globals,
518 &PyDict_Type, &locals))
519 return NULL;
520 if (globals == Py_None) {
521 globals = PyEval_GetGlobals();
522 if (locals == Py_None)
523 locals = PyEval_GetLocals();
525 else if (locals == Py_None)
526 locals = globals;
527 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
528 if (PyDict_SetItemString(globals, "__builtins__",
529 PyEval_GetBuiltins()) != 0)
530 return NULL;
532 if (PyCode_Check(cmd)) {
533 if (PyTuple_GET_SIZE(((PyCodeObject *)cmd)->co_freevars) > 0) {
534 PyErr_SetString(PyExc_TypeError,
535 "code object passed to eval() may not contain free variables");
536 return NULL;
538 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
540 if (!PyString_Check(cmd) &&
541 !PyUnicode_Check(cmd)) {
542 PyErr_SetString(PyExc_TypeError,
543 "eval() arg 1 must be a string or code object");
544 return NULL;
546 if (PyString_AsStringAndSize(cmd, &str, NULL))
547 return NULL;
548 while (*str == ' ' || *str == '\t')
549 str++;
550 return PyRun_String(str, Py_eval_input, globals, locals);
553 static char eval_doc[] =
554 "eval(source[, globals[, locals]]) -> value\n\
556 Evaluate the source in the context of globals and locals.\n\
557 The source may be a string representing a Python expression\n\
558 or a code object as returned by compile().\n\
559 The globals and locals are dictionaries, defaulting to the current\n\
560 globals and locals. If only globals is given, locals defaults to it.";
563 static PyObject *
564 builtin_execfile(PyObject *self, PyObject *args)
566 char *filename;
567 PyObject *globals = Py_None, *locals = Py_None;
568 PyObject *res;
569 FILE* fp;
570 PyCompilerFlags cf;
571 int exists;
572 struct stat s;
574 if (!PyArg_ParseTuple(args, "s|O!O!:execfile",
575 &filename,
576 &PyDict_Type, &globals,
577 &PyDict_Type, &locals))
578 return NULL;
579 if (globals == Py_None) {
580 globals = PyEval_GetGlobals();
581 if (locals == Py_None)
582 locals = PyEval_GetLocals();
584 else if (locals == Py_None)
585 locals = globals;
586 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
587 if (PyDict_SetItemString(globals, "__builtins__",
588 PyEval_GetBuiltins()) != 0)
589 return NULL;
592 exists = 0;
593 /* Test for existence or directory. */
594 if (!stat(filename, &s)) {
595 if (S_ISDIR(s.st_mode))
596 errno = EISDIR;
597 else
598 exists = 1;
601 if (exists) {
602 Py_BEGIN_ALLOW_THREADS
603 fp = fopen(filename, "r");
604 Py_END_ALLOW_THREADS
606 if (fp == NULL) {
607 exists = 0;
611 if (!exists) {
612 PyErr_SetFromErrno(PyExc_IOError);
613 return NULL;
615 cf.cf_flags = 0;
616 if (PyEval_MergeCompilerFlags(&cf))
617 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
618 locals, 1, &cf);
619 else
620 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
621 locals, 1);
622 return res;
625 static char execfile_doc[] =
626 "execfile(filename[, globals[, locals]])\n\
628 Read and execute a Python script from a file.\n\
629 The globals and locals are dictionaries, defaulting to the current\n\
630 globals and locals. If only globals is given, locals defaults to it.";
633 static PyObject *
634 builtin_getattr(PyObject *self, PyObject *args)
636 PyObject *v, *result, *dflt = NULL;
637 PyObject *name;
639 if (!PyArg_ParseTuple(args, "OO|O:getattr", &v, &name, &dflt))
640 return NULL;
641 if (PyUnicode_Check(name)) {
642 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
643 if (name == NULL)
644 return NULL;
647 if (!PyString_Check(name)) {
648 PyErr_SetString(PyExc_TypeError,
649 "attribute name must be string");
650 return NULL;
652 result = PyObject_GetAttr(v, name);
653 if (result == NULL && dflt != NULL) {
654 PyErr_Clear();
655 Py_INCREF(dflt);
656 result = dflt;
658 return result;
661 static char getattr_doc[] =
662 "getattr(object, name[, default]) -> value\n\
664 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
665 When a default argument is given, it is returned when the attribute doesn't\n\
666 exist; without it, an exception is raised in that case.";
669 static PyObject *
670 builtin_globals(PyObject *self, PyObject *args)
672 PyObject *d;
674 if (!PyArg_ParseTuple(args, ":globals"))
675 return NULL;
676 d = PyEval_GetGlobals();
677 Py_INCREF(d);
678 return d;
681 static char globals_doc[] =
682 "globals() -> dictionary\n\
684 Return the dictionary containing the current scope's global variables.";
687 static PyObject *
688 builtin_hasattr(PyObject *self, PyObject *args)
690 PyObject *v;
691 PyObject *name;
693 if (!PyArg_ParseTuple(args, "OO:hasattr", &v, &name))
694 return NULL;
695 if (PyUnicode_Check(name)) {
696 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
697 if (name == NULL)
698 return NULL;
701 if (!PyString_Check(name)) {
702 PyErr_SetString(PyExc_TypeError,
703 "attribute name must be string");
704 return NULL;
706 v = PyObject_GetAttr(v, name);
707 if (v == NULL) {
708 PyErr_Clear();
709 Py_INCREF(Py_False);
710 return Py_False;
712 Py_DECREF(v);
713 Py_INCREF(Py_True);
714 return Py_True;
717 static char hasattr_doc[] =
718 "hasattr(object, name) -> Boolean\n\
720 Return whether the object has an attribute with the given name.\n\
721 (This is done by calling getattr(object, name) and catching exceptions.)";
724 static PyObject *
725 builtin_id(PyObject *self, PyObject *args)
727 PyObject *v;
729 if (!PyArg_ParseTuple(args, "O:id", &v))
730 return NULL;
731 return PyLong_FromVoidPtr(v);
734 static char id_doc[] =
735 "id(object) -> integer\n\
737 Return the identity of an object. This is guaranteed to be unique among\n\
738 simultaneously existing objects. (Hint: it's the object's memory address.)";
741 static PyObject *
742 builtin_map(PyObject *self, PyObject *args)
744 typedef struct {
745 PyObject *it; /* the iterator object */
746 int saw_StopIteration; /* bool: did the iterator end? */
747 } sequence;
749 PyObject *func, *result;
750 sequence *seqs = NULL, *sqp;
751 int n, len;
752 register int i, j;
754 n = PyTuple_Size(args);
755 if (n < 2) {
756 PyErr_SetString(PyExc_TypeError,
757 "map() requires at least two args");
758 return NULL;
761 func = PyTuple_GetItem(args, 0);
762 n--;
764 if (func == Py_None && n == 1) {
765 /* map(None, S) is the same as list(S). */
766 return PySequence_List(PyTuple_GetItem(args, 1));
769 /* Get space for sequence descriptors. Must NULL out the iterator
770 * pointers so that jumping to Fail_2 later doesn't see trash.
772 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
773 PyErr_NoMemory();
774 return NULL;
776 for (i = 0; i < n; ++i) {
777 seqs[i].it = (PyObject*)NULL;
778 seqs[i].saw_StopIteration = 0;
781 /* Do a first pass to obtain iterators for the arguments, and set len
782 * to the largest of their lengths.
784 len = 0;
785 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
786 PyObject *curseq;
787 int curlen;
789 /* Get iterator. */
790 curseq = PyTuple_GetItem(args, i+1);
791 sqp->it = PyObject_GetIter(curseq);
792 if (sqp->it == NULL) {
793 static char errmsg[] =
794 "argument %d to map() must support iteration";
795 char errbuf[sizeof(errmsg) + 25];
796 sprintf(errbuf, errmsg, i+2);
797 PyErr_SetString(PyExc_TypeError, errbuf);
798 goto Fail_2;
801 /* Update len. */
802 curlen = -1; /* unknown */
803 if (PySequence_Check(curseq) &&
804 curseq->ob_type->tp_as_sequence->sq_length) {
805 curlen = PySequence_Size(curseq);
806 if (curlen < 0)
807 PyErr_Clear();
809 if (curlen < 0)
810 curlen = 8; /* arbitrary */
811 if (curlen > len)
812 len = curlen;
815 /* Get space for the result list. */
816 if ((result = (PyObject *) PyList_New(len)) == NULL)
817 goto Fail_2;
819 /* Iterate over the sequences until all have stopped. */
820 for (i = 0; ; ++i) {
821 PyObject *alist, *item=NULL, *value;
822 int numactive = 0;
824 if (func == Py_None && n == 1)
825 alist = NULL;
826 else if ((alist = PyTuple_New(n)) == NULL)
827 goto Fail_1;
829 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
830 if (sqp->saw_StopIteration) {
831 Py_INCREF(Py_None);
832 item = Py_None;
834 else {
835 item = PyIter_Next(sqp->it);
836 if (item)
837 ++numactive;
838 else {
839 if (PyErr_Occurred()) {
840 Py_XDECREF(alist);
841 goto Fail_1;
843 Py_INCREF(Py_None);
844 item = Py_None;
845 sqp->saw_StopIteration = 1;
848 if (alist)
849 PyTuple_SET_ITEM(alist, j, item);
850 else
851 break;
854 if (!alist)
855 alist = item;
857 if (numactive == 0) {
858 Py_DECREF(alist);
859 break;
862 if (func == Py_None)
863 value = alist;
864 else {
865 value = PyEval_CallObject(func, alist);
866 Py_DECREF(alist);
867 if (value == NULL)
868 goto Fail_1;
870 if (i >= len) {
871 int status = PyList_Append(result, value);
872 Py_DECREF(value);
873 if (status < 0)
874 goto Fail_1;
876 else if (PyList_SetItem(result, i, value) < 0)
877 goto Fail_1;
880 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
881 goto Fail_1;
883 goto Succeed;
885 Fail_1:
886 Py_DECREF(result);
887 Fail_2:
888 result = NULL;
889 Succeed:
890 assert(seqs);
891 for (i = 0; i < n; ++i)
892 Py_XDECREF(seqs[i].it);
893 PyMem_DEL(seqs);
894 return result;
897 static char map_doc[] =
898 "map(function, sequence[, sequence, ...]) -> list\n\
900 Return a list of the results of applying the function to the items of\n\
901 the argument sequence(s). If more than one sequence is given, the\n\
902 function is called with an argument list consisting of the corresponding\n\
903 item of each sequence, substituting None for missing values when not all\n\
904 sequences have the same length. If the function is None, return a list of\n\
905 the items of the sequence (or a list of tuples if more than one sequence).";
908 static PyObject *
909 builtin_setattr(PyObject *self, PyObject *args)
911 PyObject *v;
912 PyObject *name;
913 PyObject *value;
915 if (!PyArg_ParseTuple(args, "OOO:setattr", &v, &name, &value))
916 return NULL;
917 if (PyObject_SetAttr(v, name, value) != 0)
918 return NULL;
919 Py_INCREF(Py_None);
920 return Py_None;
923 static char setattr_doc[] =
924 "setattr(object, name, value)\n\
926 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
927 ``x.y = v''.";
930 static PyObject *
931 builtin_delattr(PyObject *self, PyObject *args)
933 PyObject *v;
934 PyObject *name;
936 if (!PyArg_ParseTuple(args, "OO:delattr", &v, &name))
937 return NULL;
938 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
939 return NULL;
940 Py_INCREF(Py_None);
941 return Py_None;
944 static char delattr_doc[] =
945 "delattr(object, name)\n\
947 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
948 ``del x.y''.";
951 static PyObject *
952 builtin_hash(PyObject *self, PyObject *args)
954 PyObject *v;
955 long x;
957 if (!PyArg_ParseTuple(args, "O:hash", &v))
958 return NULL;
959 x = PyObject_Hash(v);
960 if (x == -1)
961 return NULL;
962 return PyInt_FromLong(x);
965 static char hash_doc[] =
966 "hash(object) -> integer\n\
968 Return a hash value for the object. Two objects with the same value have\n\
969 the same hash value. The reverse is not necessarily true, but likely.";
972 static PyObject *
973 builtin_hex(PyObject *self, PyObject *args)
975 PyObject *v;
976 PyNumberMethods *nb;
978 if (!PyArg_ParseTuple(args, "O:hex", &v))
979 return NULL;
981 if ((nb = v->ob_type->tp_as_number) == NULL ||
982 nb->nb_hex == NULL) {
983 PyErr_SetString(PyExc_TypeError,
984 "hex() argument can't be converted to hex");
985 return NULL;
987 return (*nb->nb_hex)(v);
990 static char hex_doc[] =
991 "hex(number) -> string\n\
993 Return the hexadecimal representation of an integer or long integer.";
996 static PyObject *builtin_raw_input(PyObject *, PyObject *);
998 static PyObject *
999 builtin_input(PyObject *self, PyObject *args)
1001 PyObject *line;
1002 char *str;
1003 PyObject *res;
1004 PyObject *globals, *locals;
1006 line = builtin_raw_input(self, args);
1007 if (line == NULL)
1008 return line;
1009 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1010 return NULL;
1011 while (*str == ' ' || *str == '\t')
1012 str++;
1013 globals = PyEval_GetGlobals();
1014 locals = PyEval_GetLocals();
1015 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1016 if (PyDict_SetItemString(globals, "__builtins__",
1017 PyEval_GetBuiltins()) != 0)
1018 return NULL;
1020 res = PyRun_String(str, Py_eval_input, globals, locals);
1021 Py_DECREF(line);
1022 return res;
1025 static char input_doc[] =
1026 "input([prompt]) -> value\n\
1028 Equivalent to eval(raw_input(prompt)).";
1031 static PyObject *
1032 builtin_intern(PyObject *self, PyObject *args)
1034 PyObject *s;
1035 if (!PyArg_ParseTuple(args, "S:intern", &s))
1036 return NULL;
1037 Py_INCREF(s);
1038 PyString_InternInPlace(&s);
1039 return s;
1042 static char intern_doc[] =
1043 "intern(string) -> string\n\
1045 ``Intern'' the given string. This enters the string in the (global)\n\
1046 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1047 Return the string itself or the previously interned string object with the\n\
1048 same value.";
1051 static PyObject *
1052 builtin_iter(PyObject *self, PyObject *args)
1054 PyObject *v, *w = NULL;
1056 if (!PyArg_ParseTuple(args, "O|O:iter", &v, &w))
1057 return NULL;
1058 if (w == NULL)
1059 return PyObject_GetIter(v);
1060 if (!PyCallable_Check(v)) {
1061 PyErr_SetString(PyExc_TypeError,
1062 "iter(v, w): v must be callable");
1063 return NULL;
1065 return PyCallIter_New(v, w);
1068 static char iter_doc[] =
1069 "iter(collection) -> iterator\n\
1070 iter(callable, sentinel) -> iterator\n\
1072 Get an iterator from an object. In the first form, the argument must\n\
1073 supply its own iterator, or be a sequence.\n\
1074 In the second form, the callable is called until it returns the sentinel.";
1077 static PyObject *
1078 builtin_len(PyObject *self, PyObject *args)
1080 PyObject *v;
1081 long res;
1083 if (!PyArg_ParseTuple(args, "O:len", &v))
1084 return NULL;
1085 res = PyObject_Size(v);
1086 if (res < 0 && PyErr_Occurred())
1087 return NULL;
1088 return PyInt_FromLong(res);
1091 static char len_doc[] =
1092 "len(object) -> integer\n\
1094 Return the number of items of a sequence or mapping.";
1097 static PyObject *
1098 builtin_slice(PyObject *self, PyObject *args)
1100 PyObject *start, *stop, *step;
1102 start = stop = step = NULL;
1104 if (!PyArg_ParseTuple(args, "O|OO:slice", &start, &stop, &step))
1105 return NULL;
1107 /* This swapping of stop and start is to maintain similarity with
1108 range(). */
1109 if (stop == NULL) {
1110 stop = start;
1111 start = NULL;
1113 return PySlice_New(start, stop, step);
1116 static char slice_doc[] =
1117 "slice([start,] stop[, step]) -> slice object\n\
1119 Create a slice object. This is used for slicing by the Numeric extensions.";
1122 static PyObject *
1123 builtin_locals(PyObject *self, PyObject *args)
1125 PyObject *d;
1127 if (!PyArg_ParseTuple(args, ":locals"))
1128 return NULL;
1129 d = PyEval_GetLocals();
1130 Py_INCREF(d);
1131 return d;
1134 static char locals_doc[] =
1135 "locals() -> dictionary\n\
1137 Return the dictionary containing the current scope's local variables.";
1140 static PyObject *
1141 min_max(PyObject *args, int op)
1143 PyObject *v, *w, *x, *it;
1145 if (PyTuple_Size(args) > 1)
1146 v = args;
1147 else if (!PyArg_ParseTuple(args, "O:min/max", &v))
1148 return NULL;
1150 it = PyObject_GetIter(v);
1151 if (it == NULL)
1152 return NULL;
1154 w = NULL; /* the result */
1155 for (;;) {
1156 x = PyIter_Next(it);
1157 if (x == NULL) {
1158 if (PyErr_Occurred()) {
1159 Py_XDECREF(w);
1160 Py_DECREF(it);
1161 return NULL;
1163 break;
1166 if (w == NULL)
1167 w = x;
1168 else {
1169 int cmp = PyObject_RichCompareBool(x, w, op);
1170 if (cmp > 0) {
1171 Py_DECREF(w);
1172 w = x;
1174 else if (cmp < 0) {
1175 Py_DECREF(x);
1176 Py_DECREF(w);
1177 Py_DECREF(it);
1178 return NULL;
1180 else
1181 Py_DECREF(x);
1184 if (w == NULL)
1185 PyErr_SetString(PyExc_ValueError,
1186 "min() or max() arg is an empty sequence");
1187 Py_DECREF(it);
1188 return w;
1191 static PyObject *
1192 builtin_min(PyObject *self, PyObject *v)
1194 return min_max(v, Py_LT);
1197 static char min_doc[] =
1198 "min(sequence) -> value\n\
1199 min(a, b, c, ...) -> value\n\
1201 With a single sequence argument, return its smallest item.\n\
1202 With two or more arguments, return the smallest argument.";
1205 static PyObject *
1206 builtin_max(PyObject *self, PyObject *v)
1208 return min_max(v, Py_GT);
1211 static char max_doc[] =
1212 "max(sequence) -> value\n\
1213 max(a, b, c, ...) -> value\n\
1215 With a single sequence argument, return its largest item.\n\
1216 With two or more arguments, return the largest argument.";
1219 static PyObject *
1220 builtin_oct(PyObject *self, PyObject *args)
1222 PyObject *v;
1223 PyNumberMethods *nb;
1225 if (!PyArg_ParseTuple(args, "O:oct", &v))
1226 return NULL;
1227 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1228 nb->nb_oct == NULL) {
1229 PyErr_SetString(PyExc_TypeError,
1230 "oct() argument can't be converted to oct");
1231 return NULL;
1233 return (*nb->nb_oct)(v);
1236 static char oct_doc[] =
1237 "oct(number) -> string\n\
1239 Return the octal representation of an integer or long integer.";
1242 static PyObject *
1243 builtin_open(PyObject *self, PyObject *args)
1245 char *name = NULL;
1246 char *mode = "r";
1247 int bufsize = -1;
1248 PyObject *f;
1250 if (!PyArg_ParseTuple(args, "et|si:open", Py_FileSystemDefaultEncoding,
1251 &name, &mode, &bufsize))
1252 return NULL;
1253 f = PyFile_FromString(name, mode);
1254 PyMem_Free(name); /* free the encoded string */
1255 if (f != NULL)
1256 PyFile_SetBufSize(f, bufsize);
1257 return f;
1260 static char open_doc[] =
1261 "open(filename[, mode[, buffering]]) -> file object\n\
1263 Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n\
1264 writing or appending. The file will be created if it doesn't exist\n\
1265 when opened for writing or appending; it will be truncated when\n\
1266 opened for writing. Add a 'b' to the mode for binary files.\n\
1267 Add a '+' to the mode to allow simultaneous reading and writing.\n\
1268 If the buffering argument is given, 0 means unbuffered, 1 means line\n\
1269 buffered, and larger numbers specify the buffer size.";
1272 static PyObject *
1273 builtin_ord(PyObject *self, PyObject *args)
1275 PyObject *obj;
1276 long ord;
1277 int size;
1279 if (!PyArg_ParseTuple(args, "O:ord", &obj))
1280 return NULL;
1282 if (PyString_Check(obj)) {
1283 size = PyString_GET_SIZE(obj);
1284 if (size == 1) {
1285 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1286 return PyInt_FromLong(ord);
1288 } else if (PyUnicode_Check(obj)) {
1289 size = PyUnicode_GET_SIZE(obj);
1290 if (size == 1) {
1291 ord = (long)*PyUnicode_AS_UNICODE(obj);
1292 return PyInt_FromLong(ord);
1294 } else {
1295 PyErr_Format(PyExc_TypeError,
1296 "ord() expected string of length 1, but " \
1297 "%.200s found", obj->ob_type->tp_name);
1298 return NULL;
1301 PyErr_Format(PyExc_TypeError,
1302 "ord() expected a character, "
1303 "but string of length %d found",
1304 size);
1305 return NULL;
1308 static char ord_doc[] =
1309 "ord(c) -> integer\n\
1311 Return the integer ordinal of a one-character string.";
1314 static PyObject *
1315 builtin_pow(PyObject *self, PyObject *args)
1317 PyObject *v, *w, *z = Py_None;
1319 if (!PyArg_ParseTuple(args, "OO|O:pow", &v, &w, &z))
1320 return NULL;
1321 return PyNumber_Power(v, w, z);
1324 static char pow_doc[] =
1325 "pow(x, y[, z]) -> number\n\
1327 With two arguments, equivalent to x**y. With three arguments,\n\
1328 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).";
1331 /* Return number of items in range/xrange (lo, hi, step). step > 0
1332 * required. Return a value < 0 if & only if the true value is too
1333 * large to fit in a signed long.
1335 static long
1336 get_len_of_range(long lo, long hi, long step)
1338 /* -------------------------------------------------------------
1339 If lo >= hi, the range is empty.
1340 Else if n values are in the range, the last one is
1341 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1342 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1343 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1344 the RHS is non-negative and so truncation is the same as the
1345 floor. Letting M be the largest positive long, the worst case
1346 for the RHS numerator is hi=M, lo=-M-1, and then
1347 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1348 precision to compute the RHS exactly.
1349 ---------------------------------------------------------------*/
1350 long n = 0;
1351 if (lo < hi) {
1352 unsigned long uhi = (unsigned long)hi;
1353 unsigned long ulo = (unsigned long)lo;
1354 unsigned long diff = uhi - ulo - 1;
1355 n = (long)(diff / (unsigned long)step + 1);
1357 return n;
1360 static PyObject *
1361 builtin_range(PyObject *self, PyObject *args)
1363 long ilow = 0, ihigh = 0, istep = 1;
1364 long bign;
1365 int i, n;
1367 PyObject *v;
1369 if (PyTuple_Size(args) <= 1) {
1370 if (!PyArg_ParseTuple(args,
1371 "l;range() requires 1-3 int arguments",
1372 &ihigh))
1373 return NULL;
1375 else {
1376 if (!PyArg_ParseTuple(args,
1377 "ll|l;range() requires 1-3 int arguments",
1378 &ilow, &ihigh, &istep))
1379 return NULL;
1381 if (istep == 0) {
1382 PyErr_SetString(PyExc_ValueError, "range() arg 3 must not be zero");
1383 return NULL;
1385 if (istep > 0)
1386 bign = get_len_of_range(ilow, ihigh, istep);
1387 else
1388 bign = get_len_of_range(ihigh, ilow, -istep);
1389 n = (int)bign;
1390 if (bign < 0 || (long)n != bign) {
1391 PyErr_SetString(PyExc_OverflowError,
1392 "range() result has too many items");
1393 return NULL;
1395 v = PyList_New(n);
1396 if (v == NULL)
1397 return NULL;
1398 for (i = 0; i < n; i++) {
1399 PyObject *w = PyInt_FromLong(ilow);
1400 if (w == NULL) {
1401 Py_DECREF(v);
1402 return NULL;
1404 PyList_SET_ITEM(v, i, w);
1405 ilow += istep;
1407 return v;
1410 static char range_doc[] =
1411 "range([start,] stop[, step]) -> list of integers\n\
1413 Return a list containing an arithmetic progression of integers.\n\
1414 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1415 When step is given, it specifies the increment (or decrement).\n\
1416 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1417 These are exactly the valid indices for a list of 4 elements.";
1420 static PyObject *
1421 builtin_xrange(PyObject *self, PyObject *args)
1423 long ilow = 0, ihigh = 0, istep = 1;
1424 long n;
1426 if (PyTuple_Size(args) <= 1) {
1427 if (!PyArg_ParseTuple(args,
1428 "l;xrange() requires 1-3 int arguments",
1429 &ihigh))
1430 return NULL;
1432 else {
1433 if (!PyArg_ParseTuple(args,
1434 "ll|l;xrange() requires 1-3 int arguments",
1435 &ilow, &ihigh, &istep))
1436 return NULL;
1438 if (istep == 0) {
1439 PyErr_SetString(PyExc_ValueError, "xrange() arg 3 must not be zero");
1440 return NULL;
1442 if (istep > 0)
1443 n = get_len_of_range(ilow, ihigh, istep);
1444 else
1445 n = get_len_of_range(ihigh, ilow, -istep);
1446 if (n < 0) {
1447 PyErr_SetString(PyExc_OverflowError,
1448 "xrange() result has too many items");
1449 return NULL;
1451 return PyRange_New(ilow, n, istep, 1);
1454 static char xrange_doc[] =
1455 "xrange([start,] stop[, step]) -> xrange object\n\
1457 Like range(), but instead of returning a list, returns an object that\n\
1458 generates the numbers in the range on demand. This is slightly slower\n\
1459 than range() but more memory efficient.";
1462 static PyObject *
1463 builtin_raw_input(PyObject *self, PyObject *args)
1465 PyObject *v = NULL;
1466 PyObject *f;
1468 if (!PyArg_ParseTuple(args, "|O:[raw_]input", &v))
1469 return NULL;
1470 if (PyFile_AsFile(PySys_GetObject("stdin")) == stdin &&
1471 PyFile_AsFile(PySys_GetObject("stdout")) == stdout &&
1472 isatty(fileno(stdin)) && isatty(fileno(stdout))) {
1473 PyObject *po;
1474 char *prompt;
1475 char *s;
1476 PyObject *result;
1477 if (v != NULL) {
1478 po = PyObject_Str(v);
1479 if (po == NULL)
1480 return NULL;
1481 prompt = PyString_AsString(po);
1482 if (prompt == NULL)
1483 return NULL;
1485 else {
1486 po = NULL;
1487 prompt = "";
1489 s = PyOS_Readline(prompt);
1490 Py_XDECREF(po);
1491 if (s == NULL) {
1492 PyErr_SetNone(PyExc_KeyboardInterrupt);
1493 return NULL;
1495 if (*s == '\0') {
1496 PyErr_SetNone(PyExc_EOFError);
1497 result = NULL;
1499 else { /* strip trailing '\n' */
1500 size_t len = strlen(s);
1501 if (len > INT_MAX) {
1502 PyErr_SetString(PyExc_OverflowError, "input too long");
1503 result = NULL;
1505 else {
1506 result = PyString_FromStringAndSize(s, (int)(len-1));
1509 PyMem_FREE(s);
1510 return result;
1512 if (v != NULL) {
1513 f = PySys_GetObject("stdout");
1514 if (f == NULL) {
1515 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1516 return NULL;
1518 if (Py_FlushLine() != 0 ||
1519 PyFile_WriteObject(v, f, Py_PRINT_RAW) != 0)
1520 return NULL;
1522 f = PySys_GetObject("stdin");
1523 if (f == NULL) {
1524 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdin");
1525 return NULL;
1527 return PyFile_GetLine(f, -1);
1530 static char raw_input_doc[] =
1531 "raw_input([prompt]) -> string\n\
1533 Read a string from standard input. The trailing newline is stripped.\n\
1534 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1535 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1536 is printed without a trailing newline before reading.";
1539 static PyObject *
1540 builtin_reduce(PyObject *self, PyObject *args)
1542 PyObject *seq, *func, *result = NULL, *it;
1544 if (!PyArg_ParseTuple(args, "OO|O:reduce", &func, &seq, &result))
1545 return NULL;
1546 if (result != NULL)
1547 Py_INCREF(result);
1549 it = PyObject_GetIter(seq);
1550 if (it == NULL) {
1551 PyErr_SetString(PyExc_TypeError,
1552 "reduce() arg 2 must support iteration");
1553 Py_XDECREF(result);
1554 return NULL;
1557 if ((args = PyTuple_New(2)) == NULL)
1558 goto Fail;
1560 for (;;) {
1561 PyObject *op2;
1563 if (args->ob_refcnt > 1) {
1564 Py_DECREF(args);
1565 if ((args = PyTuple_New(2)) == NULL)
1566 goto Fail;
1569 op2 = PyIter_Next(it);
1570 if (op2 == NULL) {
1571 if (PyErr_Occurred())
1572 goto Fail;
1573 break;
1576 if (result == NULL)
1577 result = op2;
1578 else {
1579 PyTuple_SetItem(args, 0, result);
1580 PyTuple_SetItem(args, 1, op2);
1581 if ((result = PyEval_CallObject(func, args)) == NULL)
1582 goto Fail;
1586 Py_DECREF(args);
1588 if (result == NULL)
1589 PyErr_SetString(PyExc_TypeError,
1590 "reduce() of empty sequence with no initial value");
1592 Py_DECREF(it);
1593 return result;
1595 Fail:
1596 Py_XDECREF(args);
1597 Py_XDECREF(result);
1598 Py_DECREF(it);
1599 return NULL;
1602 static char reduce_doc[] =
1603 "reduce(function, sequence[, initial]) -> value\n\
1605 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1606 from left to right, so as to reduce the sequence to a single value.\n\
1607 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1608 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1609 of the sequence in the calculation, and serves as a default when the\n\
1610 sequence is empty.";
1613 static PyObject *
1614 builtin_reload(PyObject *self, PyObject *args)
1616 PyObject *v;
1618 if (!PyArg_ParseTuple(args, "O:reload", &v))
1619 return NULL;
1620 return PyImport_ReloadModule(v);
1623 static char reload_doc[] =
1624 "reload(module) -> module\n\
1626 Reload the module. The module must have been successfully imported before.";
1629 static PyObject *
1630 builtin_repr(PyObject *self, PyObject *args)
1632 PyObject *v;
1634 if (!PyArg_ParseTuple(args, "O:repr", &v))
1635 return NULL;
1636 return PyObject_Repr(v);
1639 static char repr_doc[] =
1640 "repr(object) -> string\n\
1642 Return the canonical string representation of the object.\n\
1643 For most object types, eval(repr(object)) == object.";
1646 static PyObject *
1647 builtin_round(PyObject *self, PyObject *args)
1649 double x;
1650 double f;
1651 int ndigits = 0;
1652 int i;
1654 if (!PyArg_ParseTuple(args, "d|i:round", &x, &ndigits))
1655 return NULL;
1656 f = 1.0;
1657 i = abs(ndigits);
1658 while (--i >= 0)
1659 f = f*10.0;
1660 if (ndigits < 0)
1661 x /= f;
1662 else
1663 x *= f;
1664 if (x >= 0.0)
1665 x = floor(x + 0.5);
1666 else
1667 x = ceil(x - 0.5);
1668 if (ndigits < 0)
1669 x *= f;
1670 else
1671 x /= f;
1672 return PyFloat_FromDouble(x);
1675 static char round_doc[] =
1676 "round(number[, ndigits]) -> floating point number\n\
1678 Round a number to a given precision in decimal digits (default 0 digits).\n\
1679 This always returns a floating point number. Precision may be negative.";
1682 static PyObject *
1683 builtin_vars(PyObject *self, PyObject *args)
1685 PyObject *v = NULL;
1686 PyObject *d;
1688 if (!PyArg_ParseTuple(args, "|O:vars", &v))
1689 return NULL;
1690 if (v == NULL) {
1691 d = PyEval_GetLocals();
1692 if (d == NULL) {
1693 if (!PyErr_Occurred())
1694 PyErr_SetString(PyExc_SystemError,
1695 "no locals!?");
1697 else
1698 Py_INCREF(d);
1700 else {
1701 d = PyObject_GetAttrString(v, "__dict__");
1702 if (d == NULL) {
1703 PyErr_SetString(PyExc_TypeError,
1704 "vars() argument must have __dict__ attribute");
1705 return NULL;
1708 return d;
1711 static char vars_doc[] =
1712 "vars([object]) -> dictionary\n\
1714 Without arguments, equivalent to locals().\n\
1715 With an argument, equivalent to object.__dict__.";
1717 static PyObject *
1718 builtin_isinstance(PyObject *self, PyObject *args)
1720 PyObject *inst;
1721 PyObject *cls;
1722 int retval;
1724 if (!PyArg_ParseTuple(args, "OO:isinstance", &inst, &cls))
1725 return NULL;
1727 retval = PyObject_IsInstance(inst, cls);
1728 if (retval < 0)
1729 return NULL;
1730 return PyInt_FromLong(retval);
1733 static char isinstance_doc[] =
1734 "isinstance(object, class-or-type) -> Boolean\n\
1736 Return whether an object is an instance of a class or of a subclass thereof.\n\
1737 With a type as second argument, return whether that is the object's type.";
1740 static PyObject *
1741 builtin_issubclass(PyObject *self, PyObject *args)
1743 PyObject *derived;
1744 PyObject *cls;
1745 int retval;
1747 if (!PyArg_ParseTuple(args, "OO:issubclass", &derived, &cls))
1748 return NULL;
1750 retval = PyObject_IsSubclass(derived, cls);
1751 if (retval < 0)
1752 return NULL;
1753 return PyInt_FromLong(retval);
1756 static char issubclass_doc[] =
1757 "issubclass(C, B) -> Boolean\n\
1759 Return whether class C is a subclass (i.e., a derived class) of class B.";
1762 static PyObject*
1763 builtin_zip(PyObject *self, PyObject *args)
1765 PyObject *ret;
1766 int itemsize = PySequence_Length(args);
1767 int i;
1768 PyObject *itlist; /* tuple of iterators */
1770 if (itemsize < 1) {
1771 PyErr_SetString(PyExc_TypeError,
1772 "zip() requires at least one sequence");
1773 return NULL;
1775 /* args must be a tuple */
1776 assert(PyTuple_Check(args));
1778 /* allocate result list */
1779 if ((ret = PyList_New(0)) == NULL)
1780 return NULL;
1782 /* obtain iterators */
1783 itlist = PyTuple_New(itemsize);
1784 if (itlist == NULL)
1785 goto Fail_ret;
1786 for (i = 0; i < itemsize; ++i) {
1787 PyObject *item = PyTuple_GET_ITEM(args, i);
1788 PyObject *it = PyObject_GetIter(item);
1789 if (it == NULL) {
1790 if (PyErr_ExceptionMatches(PyExc_TypeError))
1791 PyErr_Format(PyExc_TypeError,
1792 "zip argument #%d must support iteration",
1793 i+1);
1794 goto Fail_ret_itlist;
1796 PyTuple_SET_ITEM(itlist, i, it);
1799 /* build result into ret list */
1800 for (;;) {
1801 int status;
1802 PyObject *next = PyTuple_New(itemsize);
1803 if (!next)
1804 goto Fail_ret_itlist;
1806 for (i = 0; i < itemsize; i++) {
1807 PyObject *it = PyTuple_GET_ITEM(itlist, i);
1808 PyObject *item = PyIter_Next(it);
1809 if (!item) {
1810 if (PyErr_Occurred()) {
1811 Py_DECREF(ret);
1812 ret = NULL;
1814 Py_DECREF(next);
1815 Py_DECREF(itlist);
1816 return ret;
1818 PyTuple_SET_ITEM(next, i, item);
1821 status = PyList_Append(ret, next);
1822 Py_DECREF(next);
1823 if (status < 0)
1824 goto Fail_ret_itlist;
1827 Fail_ret_itlist:
1828 Py_DECREF(itlist);
1829 Fail_ret:
1830 Py_DECREF(ret);
1831 return NULL;
1835 static char zip_doc[] =
1836 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
1838 Return a list of tuples, where each tuple contains the i-th element\n\
1839 from each of the argument sequences. The returned list is truncated\n\
1840 in length to the length of the shortest argument sequence.";
1843 static PyMethodDef builtin_methods[] = {
1844 {"__import__", builtin___import__, 1, import_doc},
1845 {"abs", builtin_abs, 1, abs_doc},
1846 {"apply", builtin_apply, 1, apply_doc},
1847 {"buffer", builtin_buffer, 1, buffer_doc},
1848 {"callable", builtin_callable, 1, callable_doc},
1849 {"chr", builtin_chr, 1, chr_doc},
1850 {"cmp", builtin_cmp, 1, cmp_doc},
1851 {"coerce", builtin_coerce, 1, coerce_doc},
1852 {"compile", builtin_compile, 1, compile_doc},
1853 {"delattr", builtin_delattr, 1, delattr_doc},
1854 {"dir", builtin_dir, 1, dir_doc},
1855 {"divmod", builtin_divmod, 1, divmod_doc},
1856 {"eval", builtin_eval, 1, eval_doc},
1857 {"execfile", builtin_execfile, 1, execfile_doc},
1858 {"filter", builtin_filter, 1, filter_doc},
1859 {"getattr", builtin_getattr, 1, getattr_doc},
1860 {"globals", builtin_globals, 1, globals_doc},
1861 {"hasattr", builtin_hasattr, 1, hasattr_doc},
1862 {"hash", builtin_hash, 1, hash_doc},
1863 {"hex", builtin_hex, 1, hex_doc},
1864 {"id", builtin_id, 1, id_doc},
1865 {"input", builtin_input, 1, input_doc},
1866 {"intern", builtin_intern, 1, intern_doc},
1867 {"isinstance", builtin_isinstance, 1, isinstance_doc},
1868 {"issubclass", builtin_issubclass, 1, issubclass_doc},
1869 {"iter", builtin_iter, 1, iter_doc},
1870 {"len", builtin_len, 1, len_doc},
1871 {"locals", builtin_locals, 1, locals_doc},
1872 {"map", builtin_map, 1, map_doc},
1873 {"max", builtin_max, 1, max_doc},
1874 {"min", builtin_min, 1, min_doc},
1875 {"oct", builtin_oct, 1, oct_doc},
1876 {"open", builtin_open, 1, open_doc},
1877 {"ord", builtin_ord, 1, ord_doc},
1878 {"pow", builtin_pow, 1, pow_doc},
1879 {"range", builtin_range, 1, range_doc},
1880 {"raw_input", builtin_raw_input, 1, raw_input_doc},
1881 {"reduce", builtin_reduce, 1, reduce_doc},
1882 {"reload", builtin_reload, 1, reload_doc},
1883 {"repr", builtin_repr, 1, repr_doc},
1884 {"round", builtin_round, 1, round_doc},
1885 {"setattr", builtin_setattr, 1, setattr_doc},
1886 {"slice", builtin_slice, 1, slice_doc},
1887 {"unichr", builtin_unichr, 1, unichr_doc},
1888 {"vars", builtin_vars, 1, vars_doc},
1889 {"xrange", builtin_xrange, 1, xrange_doc},
1890 {"zip", builtin_zip, 1, zip_doc},
1891 {NULL, NULL},
1894 static char builtin_doc[] =
1895 "Built-in functions, exceptions, and other objects.\n\
1897 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.";
1899 PyObject *
1900 _PyBuiltin_Init(void)
1902 PyObject *mod, *dict, *debug;
1903 mod = Py_InitModule4("__builtin__", builtin_methods,
1904 builtin_doc, (PyObject *)NULL,
1905 PYTHON_API_VERSION);
1906 if (mod == NULL)
1907 return NULL;
1908 dict = PyModule_GetDict(mod);
1909 if (PyDict_SetItemString(dict, "None", Py_None) < 0)
1910 return NULL;
1911 if (PyDict_SetItemString(dict, "Ellipsis", Py_Ellipsis) < 0)
1912 return NULL;
1913 if (PyDict_SetItemString(dict, "NotImplemented",
1914 Py_NotImplemented) < 0)
1915 return NULL;
1916 if (PyDict_SetItemString(dict, "classmethod",
1917 (PyObject *) &PyClassMethod_Type) < 0)
1918 return NULL;
1919 #ifndef WITHOUT_COMPLEX
1920 if (PyDict_SetItemString(dict, "complex",
1921 (PyObject *) &PyComplex_Type) < 0)
1922 return NULL;
1923 #endif
1924 if (PyDict_SetItemString(dict, "dictionary",
1925 (PyObject *) &PyDict_Type) < 0)
1926 return NULL;
1927 if (PyDict_SetItemString(dict, "float",
1928 (PyObject *) &PyFloat_Type) < 0)
1929 return NULL;
1930 if (PyDict_SetItemString(dict, "int", (PyObject *) &PyInt_Type) < 0)
1931 return NULL;
1932 if (PyDict_SetItemString(dict, "list", (PyObject *) &PyList_Type) < 0)
1933 return NULL;
1934 if (PyDict_SetItemString(dict, "long", (PyObject *) &PyLong_Type) < 0)
1935 return NULL;
1936 if (PyDict_SetItemString(dict, "object",
1937 (PyObject *) &PyBaseObject_Type) < 0)
1938 return NULL;
1939 if (PyDict_SetItemString(dict, "staticmethod",
1940 (PyObject *) &PyStaticMethod_Type) < 0)
1941 return NULL;
1942 if (PyDict_SetItemString(dict, "str", (PyObject *) &PyString_Type) < 0)
1943 return NULL;
1944 if (PyDict_SetItemString(dict, "tuple",
1945 (PyObject *) &PyTuple_Type) < 0)
1946 return NULL;
1947 if (PyDict_SetItemString(dict, "type", (PyObject *) &PyType_Type) < 0)
1948 return NULL;
1949 if (PyDict_SetItemString(dict, "unicode",
1950 (PyObject *) &PyUnicode_Type) < 0)
1951 return NULL;
1952 debug = PyInt_FromLong(Py_OptimizeFlag == 0);
1953 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
1954 Py_XDECREF(debug);
1955 return NULL;
1957 Py_XDECREF(debug);
1959 return mod;
1962 /* Helper for filter(): filter a tuple through a function */
1964 static PyObject *
1965 filtertuple(PyObject *func, PyObject *tuple)
1967 PyObject *result;
1968 register int i, j;
1969 int len = PyTuple_Size(tuple);
1971 if (len == 0) {
1972 Py_INCREF(tuple);
1973 return tuple;
1976 if ((result = PyTuple_New(len)) == NULL)
1977 return NULL;
1979 for (i = j = 0; i < len; ++i) {
1980 PyObject *item, *good;
1981 int ok;
1983 if ((item = PyTuple_GetItem(tuple, i)) == NULL)
1984 goto Fail_1;
1985 if (func == Py_None) {
1986 Py_INCREF(item);
1987 good = item;
1989 else {
1990 PyObject *arg = Py_BuildValue("(O)", item);
1991 if (arg == NULL)
1992 goto Fail_1;
1993 good = PyEval_CallObject(func, arg);
1994 Py_DECREF(arg);
1995 if (good == NULL)
1996 goto Fail_1;
1998 ok = PyObject_IsTrue(good);
1999 Py_DECREF(good);
2000 if (ok) {
2001 Py_INCREF(item);
2002 if (PyTuple_SetItem(result, j++, item) < 0)
2003 goto Fail_1;
2007 if (_PyTuple_Resize(&result, j) < 0)
2008 return NULL;
2010 return result;
2012 Fail_1:
2013 Py_DECREF(result);
2014 return NULL;
2018 /* Helper for filter(): filter a string through a function */
2020 static PyObject *
2021 filterstring(PyObject *func, PyObject *strobj)
2023 PyObject *result;
2024 register int i, j;
2025 int len = PyString_Size(strobj);
2027 if (func == Py_None) {
2028 /* No character is ever false -- share input string */
2029 Py_INCREF(strobj);
2030 return strobj;
2032 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2033 return NULL;
2035 for (i = j = 0; i < len; ++i) {
2036 PyObject *item, *arg, *good;
2037 int ok;
2039 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2040 if (item == NULL)
2041 goto Fail_1;
2042 arg = Py_BuildValue("(O)", item);
2043 if (arg == NULL) {
2044 Py_DECREF(item);
2045 goto Fail_1;
2047 good = PyEval_CallObject(func, arg);
2048 Py_DECREF(arg);
2049 if (good == NULL) {
2050 Py_DECREF(item);
2051 goto Fail_1;
2053 ok = PyObject_IsTrue(good);
2054 Py_DECREF(good);
2055 if (ok)
2056 PyString_AS_STRING((PyStringObject *)result)[j++] =
2057 PyString_AS_STRING((PyStringObject *)item)[0];
2058 Py_DECREF(item);
2061 if (j < len && _PyString_Resize(&result, j) < 0)
2062 return NULL;
2064 return result;
2066 Fail_1:
2067 Py_DECREF(result);
2068 return NULL;