New \grammartoken markup, similar to \token but allowed everywhere.
[python/dscho.git] / Python / bltinmodule.c
blob9a6f5e411a475535ed1aca2f2383b5e2d37f0859
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 *v)
58 return PyNumber_Absolute(v);
61 static char 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 static char 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_buffer(PyObject *self, PyObject *args)
112 PyObject *ob;
113 int offset = 0;
114 int size = Py_END_OF_BUFFER;
116 if ( !PyArg_ParseTuple(args, "O|ii:buffer", &ob, &offset, &size) )
117 return NULL;
118 return PyBuffer_FromObject(ob, offset, size);
121 static char buffer_doc[] =
122 "buffer(object [, offset[, size]]) -> object\n\
124 Create a new buffer object which references the given object.\n\
125 The buffer will reference a slice of the target object from the\n\
126 start of the object (or at the specified offset). The slice will\n\
127 extend to the end of the target object (or with the specified size).";
130 static PyObject *
131 builtin_callable(PyObject *self, PyObject *v)
133 return PyInt_FromLong((long)PyCallable_Check(v));
136 static char callable_doc[] =
137 "callable(object) -> Boolean\n\
139 Return whether the object is callable (i.e., some kind of function).\n\
140 Note that classes are callable, as are instances with a __call__() method.";
143 static PyObject *
144 builtin_filter(PyObject *self, PyObject *args)
146 PyObject *func, *seq, *result, *it;
147 int len; /* guess for result list size */
148 register int j;
150 if (!PyArg_ParseTuple(args, "OO:filter", &func, &seq))
151 return NULL;
153 /* Strings and tuples return a result of the same type. */
154 if (PyString_Check(seq))
155 return filterstring(func, seq);
156 if (PyTuple_Check(seq))
157 return filtertuple(func, seq);
159 /* Get iterator. */
160 it = PyObject_GetIter(seq);
161 if (it == NULL)
162 return NULL;
164 /* Guess a result list size. */
165 len = -1; /* unknown */
166 if (PySequence_Check(seq) &&
167 seq->ob_type->tp_as_sequence->sq_length) {
168 len = PySequence_Size(seq);
169 if (len < 0)
170 PyErr_Clear();
172 if (len < 0)
173 len = 8; /* arbitrary */
175 /* Get a result list. */
176 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
177 /* Eww - can modify the list in-place. */
178 Py_INCREF(seq);
179 result = seq;
181 else {
182 result = PyList_New(len);
183 if (result == NULL)
184 goto Fail_it;
187 /* Build the result list. */
188 j = 0;
189 for (;;) {
190 PyObject *item, *good;
191 int ok;
193 item = PyIter_Next(it);
194 if (item == NULL) {
195 if (PyErr_Occurred())
196 goto Fail_result_it;
197 break;
200 if (func == Py_None) {
201 good = item;
202 Py_INCREF(good);
204 else {
205 PyObject *arg = Py_BuildValue("(O)", item);
206 if (arg == NULL) {
207 Py_DECREF(item);
208 goto Fail_result_it;
210 good = PyEval_CallObject(func, arg);
211 Py_DECREF(arg);
212 if (good == NULL) {
213 Py_DECREF(item);
214 goto Fail_result_it;
217 ok = PyObject_IsTrue(good);
218 Py_DECREF(good);
219 if (ok) {
220 if (j < len)
221 PyList_SET_ITEM(result, j, item);
222 else {
223 int status = PyList_Append(result, item);
224 Py_DECREF(item);
225 if (status < 0)
226 goto Fail_result_it;
228 ++j;
230 else
231 Py_DECREF(item);
235 /* Cut back result list if len is too big. */
236 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
237 goto Fail_result_it;
239 Py_DECREF(it);
240 return result;
242 Fail_result_it:
243 Py_DECREF(result);
244 Fail_it:
245 Py_DECREF(it);
246 return NULL;
249 static char filter_doc[] =
250 "filter(function, sequence) -> list\n\
252 Return a list containing those items of sequence for which function(item)\n\
253 is true. If function is None, return a list of items that are true.";
256 static PyObject *
257 builtin_chr(PyObject *self, PyObject *args)
259 long x;
260 char s[1];
262 if (!PyArg_ParseTuple(args, "l:chr", &x))
263 return NULL;
264 if (x < 0 || x >= 256) {
265 PyErr_SetString(PyExc_ValueError,
266 "chr() arg not in range(256)");
267 return NULL;
269 s[0] = (char)x;
270 return PyString_FromStringAndSize(s, 1);
273 static char chr_doc[] =
274 "chr(i) -> character\n\
276 Return a string of one character with ordinal i; 0 <= i < 256.";
279 #ifdef Py_USING_UNICODE
280 static PyObject *
281 builtin_unichr(PyObject *self, PyObject *args)
283 long x;
284 Py_UNICODE s[2];
286 if (!PyArg_ParseTuple(args, "l:unichr", &x))
287 return NULL;
289 #ifdef Py_UNICODE_WIDE
290 if (x < 0 || x > 0x10ffff) {
291 PyErr_SetString(PyExc_ValueError,
292 "unichr() arg not in range(0x110000) "
293 "(wide Python build)");
294 return NULL;
296 #else
297 if (x < 0 || x > 0xffff) {
298 PyErr_SetString(PyExc_ValueError,
299 "unichr() arg not in range(0x10000) "
300 "(narrow Python build)");
301 return NULL;
303 #endif
305 if (x <= 0xffff) {
306 /* UCS-2 character */
307 s[0] = (Py_UNICODE) x;
308 return PyUnicode_FromUnicode(s, 1);
310 else {
311 #ifndef Py_UNICODE_WIDE
312 /* UCS-4 character. store as two surrogate characters */
313 x -= 0x10000L;
314 s[0] = 0xD800 + (Py_UNICODE) (x >> 10);
315 s[1] = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
316 return PyUnicode_FromUnicode(s, 2);
317 #else
318 s[0] = (Py_UNICODE)x;
319 return PyUnicode_FromUnicode(s, 1);
320 #endif
324 static char unichr_doc[] =
325 "unichr(i) -> Unicode character\n\
327 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.";
328 #endif
331 static PyObject *
332 builtin_cmp(PyObject *self, PyObject *args)
334 PyObject *a, *b;
335 int c;
337 if (!PyArg_ParseTuple(args, "OO:cmp", &a, &b))
338 return NULL;
339 if (PyObject_Cmp(a, b, &c) < 0)
340 return NULL;
341 return PyInt_FromLong((long)c);
344 static char cmp_doc[] =
345 "cmp(x, y) -> integer\n\
347 Return negative if x<y, zero if x==y, positive if x>y.";
350 static PyObject *
351 builtin_coerce(PyObject *self, PyObject *args)
353 PyObject *v, *w;
354 PyObject *res;
356 if (!PyArg_ParseTuple(args, "OO:coerce", &v, &w))
357 return NULL;
358 if (PyNumber_Coerce(&v, &w) < 0)
359 return NULL;
360 res = Py_BuildValue("(OO)", v, w);
361 Py_DECREF(v);
362 Py_DECREF(w);
363 return res;
366 static char coerce_doc[] =
367 "coerce(x, y) -> None or (x1, y1)\n\
369 When x and y can be coerced to values of the same type, return a tuple\n\
370 containing the coerced values. When they can't be coerced, return None.";
373 static PyObject *
374 builtin_compile(PyObject *self, PyObject *args)
376 char *str;
377 char *filename;
378 char *startstr;
379 int start;
380 int dont_inherit = 0;
381 int supplied_flags = 0;
382 PyCompilerFlags cf;
384 if (!PyArg_ParseTuple(args, "sss|ii:compile", &str, &filename,
385 &startstr, &supplied_flags, &dont_inherit))
386 return NULL;
388 if (strcmp(startstr, "exec") == 0)
389 start = Py_file_input;
390 else if (strcmp(startstr, "eval") == 0)
391 start = Py_eval_input;
392 else if (strcmp(startstr, "single") == 0)
393 start = Py_single_input;
394 else {
395 PyErr_SetString(PyExc_ValueError,
396 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
397 return NULL;
400 if (supplied_flags & ~(PyCF_MASK | PyCF_MASK_OBSOLETE)) {
401 PyErr_SetString(PyExc_ValueError,
402 "compile(): unrecognised flags");
403 return NULL;
405 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
407 cf.cf_flags = supplied_flags;
408 if (!dont_inherit) {
409 PyEval_MergeCompilerFlags(&cf);
411 return Py_CompileStringFlags(str, filename, start, &cf);
414 static char compile_doc[] =
415 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
417 Compile the source string (a Python module, statement or expression)\n\
418 into a code object that can be executed by the exec statement or eval().\n\
419 The filename will be used for run-time error messages.\n\
420 The mode must be 'exec' to compile a module, 'single' to compile a\n\
421 single (interactive) statement, or 'eval' to compile an expression.\n\
422 The flags argument, if present, controls which future statements influence\n\
423 the compilation of the code.\n\
424 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
425 the effects of any future statements in effect in the code calling\n\
426 compile; if absent or zero these statements do influence the compilation,\n\
427 in addition to any features explicitly specified.";
430 static PyObject *
431 builtin_dir(PyObject *self, PyObject *args)
433 static char *attrlist[] = {"__members__", "__methods__", NULL};
434 PyObject *v = NULL, *l = NULL, *m = NULL;
435 PyObject *d, *x;
436 int i;
437 char **s;
439 if (!PyArg_ParseTuple(args, "|O:dir", &v))
440 return NULL;
441 if (v == NULL) {
442 x = PyEval_GetLocals();
443 if (x == NULL)
444 goto error;
445 l = PyMapping_Keys(x);
446 if (l == NULL)
447 goto error;
449 else {
450 d = PyObject_GetAttrString(v, "__dict__");
451 if (d == NULL)
452 PyErr_Clear();
453 else {
454 l = PyMapping_Keys(d);
455 if (l == NULL)
456 PyErr_Clear();
457 Py_DECREF(d);
459 if (l == NULL) {
460 l = PyList_New(0);
461 if (l == NULL)
462 goto error;
464 for (s = attrlist; *s != NULL; s++) {
465 m = PyObject_GetAttrString(v, *s);
466 if (m == NULL) {
467 PyErr_Clear();
468 continue;
470 for (i = 0; ; i++) {
471 x = PySequence_GetItem(m, i);
472 if (x == NULL) {
473 PyErr_Clear();
474 break;
476 if (PyList_Append(l, x) != 0) {
477 Py_DECREF(x);
478 Py_DECREF(m);
479 goto error;
481 Py_DECREF(x);
483 Py_DECREF(m);
486 if (PyList_Sort(l) != 0)
487 goto error;
488 return l;
489 error:
490 Py_XDECREF(l);
491 return NULL;
494 static char dir_doc[] =
495 "dir([object]) -> list of strings\n\
497 Return an alphabetized list of names comprising (some of) the attributes\n\
498 of the given object. Without an argument, the names in the current scope\n\
499 are listed. With an instance argument, only the instance attributes are\n\
500 returned. With a class argument, attributes of the base class are not\n\
501 returned. For other types or arguments, this may list members or methods.";
504 static PyObject *
505 builtin_divmod(PyObject *self, PyObject *args)
507 PyObject *v, *w;
509 if (!PyArg_ParseTuple(args, "OO:divmod", &v, &w))
510 return NULL;
511 return PyNumber_Divmod(v, w);
514 static char divmod_doc[] =
515 "divmod(x, y) -> (div, mod)\n\
517 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.";
520 static PyObject *
521 builtin_eval(PyObject *self, PyObject *args)
523 PyObject *cmd;
524 PyObject *globals = Py_None, *locals = Py_None;
525 char *str;
526 PyCompilerFlags cf;
528 if (!PyArg_ParseTuple(args, "O|O!O!:eval",
529 &cmd,
530 &PyDict_Type, &globals,
531 &PyDict_Type, &locals))
532 return NULL;
533 if (globals == Py_None) {
534 globals = PyEval_GetGlobals();
535 if (locals == Py_None)
536 locals = PyEval_GetLocals();
538 else if (locals == Py_None)
539 locals = globals;
541 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
542 if (PyDict_SetItemString(globals, "__builtins__",
543 PyEval_GetBuiltins()) != 0)
544 return NULL;
547 if (PyCode_Check(cmd)) {
548 if (PyTuple_GET_SIZE(((PyCodeObject *)cmd)->co_freevars) > 0) {
549 PyErr_SetString(PyExc_TypeError,
550 "code object passed to eval() may not contain free variables");
551 return NULL;
553 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
556 if (!PyString_Check(cmd) &&
557 !PyUnicode_Check(cmd)) {
558 PyErr_SetString(PyExc_TypeError,
559 "eval() arg 1 must be a string or code object");
560 return NULL;
562 if (PyString_AsStringAndSize(cmd, &str, NULL))
563 return NULL;
564 while (*str == ' ' || *str == '\t')
565 str++;
567 cf.cf_flags = 0;
568 (void)PyEval_MergeCompilerFlags(&cf);
569 return PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
572 static char eval_doc[] =
573 "eval(source[, globals[, locals]]) -> value\n\
575 Evaluate the source in the context of globals and locals.\n\
576 The source may be a string representing a Python expression\n\
577 or a code object as returned by compile().\n\
578 The globals and locals are dictionaries, defaulting to the current\n\
579 globals and locals. If only globals is given, locals defaults to it.";
582 static PyObject *
583 builtin_execfile(PyObject *self, PyObject *args)
585 char *filename;
586 PyObject *globals = Py_None, *locals = Py_None;
587 PyObject *res;
588 FILE* fp;
589 PyCompilerFlags cf;
590 int exists;
591 struct stat s;
593 if (!PyArg_ParseTuple(args, "s|O!O!:execfile",
594 &filename,
595 &PyDict_Type, &globals,
596 &PyDict_Type, &locals))
597 return NULL;
598 if (globals == Py_None) {
599 globals = PyEval_GetGlobals();
600 if (locals == Py_None)
601 locals = PyEval_GetLocals();
603 else if (locals == Py_None)
604 locals = globals;
605 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
606 if (PyDict_SetItemString(globals, "__builtins__",
607 PyEval_GetBuiltins()) != 0)
608 return NULL;
611 exists = 0;
612 /* Test for existence or directory. */
613 if (!stat(filename, &s)) {
614 if (S_ISDIR(s.st_mode))
615 errno = EISDIR;
616 else
617 exists = 1;
620 if (exists) {
621 Py_BEGIN_ALLOW_THREADS
622 fp = fopen(filename, "r");
623 Py_END_ALLOW_THREADS
625 if (fp == NULL) {
626 exists = 0;
630 if (!exists) {
631 PyErr_SetFromErrno(PyExc_IOError);
632 return NULL;
634 cf.cf_flags = 0;
635 if (PyEval_MergeCompilerFlags(&cf))
636 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
637 locals, 1, &cf);
638 else
639 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
640 locals, 1);
641 return res;
644 static char execfile_doc[] =
645 "execfile(filename[, globals[, locals]])\n\
647 Read and execute a Python script from a file.\n\
648 The globals and locals are dictionaries, defaulting to the current\n\
649 globals and locals. If only globals is given, locals defaults to it.";
652 static PyObject *
653 builtin_getattr(PyObject *self, PyObject *args)
655 PyObject *v, *result, *dflt = NULL;
656 PyObject *name;
658 if (!PyArg_ParseTuple(args, "OO|O:getattr", &v, &name, &dflt))
659 return NULL;
660 #ifdef Py_USING_UNICODE
661 if (PyUnicode_Check(name)) {
662 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
663 if (name == NULL)
664 return NULL;
666 #endif
668 if (!PyString_Check(name)) {
669 PyErr_SetString(PyExc_TypeError,
670 "attribute name must be string");
671 return NULL;
673 result = PyObject_GetAttr(v, name);
674 if (result == NULL && dflt != NULL) {
675 PyErr_Clear();
676 Py_INCREF(dflt);
677 result = dflt;
679 return result;
682 static char getattr_doc[] =
683 "getattr(object, name[, default]) -> value\n\
685 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
686 When a default argument is given, it is returned when the attribute doesn't\n\
687 exist; without it, an exception is raised in that case.";
690 static PyObject *
691 builtin_globals(PyObject *self)
693 PyObject *d;
695 d = PyEval_GetGlobals();
696 Py_INCREF(d);
697 return d;
700 static char globals_doc[] =
701 "globals() -> dictionary\n\
703 Return the dictionary containing the current scope's global variables.";
706 static PyObject *
707 builtin_hasattr(PyObject *self, PyObject *args)
709 PyObject *v;
710 PyObject *name;
712 if (!PyArg_ParseTuple(args, "OO:hasattr", &v, &name))
713 return NULL;
714 #ifdef Py_USING_UNICODE
715 if (PyUnicode_Check(name)) {
716 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
717 if (name == NULL)
718 return NULL;
720 #endif
722 if (!PyString_Check(name)) {
723 PyErr_SetString(PyExc_TypeError,
724 "attribute name must be string");
725 return NULL;
727 v = PyObject_GetAttr(v, name);
728 if (v == NULL) {
729 PyErr_Clear();
730 Py_INCREF(Py_False);
731 return Py_False;
733 Py_DECREF(v);
734 Py_INCREF(Py_True);
735 return Py_True;
738 static char hasattr_doc[] =
739 "hasattr(object, name) -> Boolean\n\
741 Return whether the object has an attribute with the given name.\n\
742 (This is done by calling getattr(object, name) and catching exceptions.)";
745 static PyObject *
746 builtin_id(PyObject *self, PyObject *v)
748 return PyLong_FromVoidPtr(v);
751 static char id_doc[] =
752 "id(object) -> integer\n\
754 Return the identity of an object. This is guaranteed to be unique among\n\
755 simultaneously existing objects. (Hint: it's the object's memory address.)";
758 static PyObject *
759 builtin_map(PyObject *self, PyObject *args)
761 typedef struct {
762 PyObject *it; /* the iterator object */
763 int saw_StopIteration; /* bool: did the iterator end? */
764 } sequence;
766 PyObject *func, *result;
767 sequence *seqs = NULL, *sqp;
768 int n, len;
769 register int i, j;
771 n = PyTuple_Size(args);
772 if (n < 2) {
773 PyErr_SetString(PyExc_TypeError,
774 "map() requires at least two args");
775 return NULL;
778 func = PyTuple_GetItem(args, 0);
779 n--;
781 if (func == Py_None && n == 1) {
782 /* map(None, S) is the same as list(S). */
783 return PySequence_List(PyTuple_GetItem(args, 1));
786 /* Get space for sequence descriptors. Must NULL out the iterator
787 * pointers so that jumping to Fail_2 later doesn't see trash.
789 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
790 PyErr_NoMemory();
791 return NULL;
793 for (i = 0; i < n; ++i) {
794 seqs[i].it = (PyObject*)NULL;
795 seqs[i].saw_StopIteration = 0;
798 /* Do a first pass to obtain iterators for the arguments, and set len
799 * to the largest of their lengths.
801 len = 0;
802 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
803 PyObject *curseq;
804 int curlen;
806 /* Get iterator. */
807 curseq = PyTuple_GetItem(args, i+1);
808 sqp->it = PyObject_GetIter(curseq);
809 if (sqp->it == NULL) {
810 static char errmsg[] =
811 "argument %d to map() must support iteration";
812 char errbuf[sizeof(errmsg) + 25];
813 sprintf(errbuf, errmsg, i+2);
814 PyErr_SetString(PyExc_TypeError, errbuf);
815 goto Fail_2;
818 /* Update len. */
819 curlen = -1; /* unknown */
820 if (PySequence_Check(curseq) &&
821 curseq->ob_type->tp_as_sequence->sq_length) {
822 curlen = PySequence_Size(curseq);
823 if (curlen < 0)
824 PyErr_Clear();
826 if (curlen < 0)
827 curlen = 8; /* arbitrary */
828 if (curlen > len)
829 len = curlen;
832 /* Get space for the result list. */
833 if ((result = (PyObject *) PyList_New(len)) == NULL)
834 goto Fail_2;
836 /* Iterate over the sequences until all have stopped. */
837 for (i = 0; ; ++i) {
838 PyObject *alist, *item=NULL, *value;
839 int numactive = 0;
841 if (func == Py_None && n == 1)
842 alist = NULL;
843 else if ((alist = PyTuple_New(n)) == NULL)
844 goto Fail_1;
846 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
847 if (sqp->saw_StopIteration) {
848 Py_INCREF(Py_None);
849 item = Py_None;
851 else {
852 item = PyIter_Next(sqp->it);
853 if (item)
854 ++numactive;
855 else {
856 if (PyErr_Occurred()) {
857 Py_XDECREF(alist);
858 goto Fail_1;
860 Py_INCREF(Py_None);
861 item = Py_None;
862 sqp->saw_StopIteration = 1;
865 if (alist)
866 PyTuple_SET_ITEM(alist, j, item);
867 else
868 break;
871 if (!alist)
872 alist = item;
874 if (numactive == 0) {
875 Py_DECREF(alist);
876 break;
879 if (func == Py_None)
880 value = alist;
881 else {
882 value = PyEval_CallObject(func, alist);
883 Py_DECREF(alist);
884 if (value == NULL)
885 goto Fail_1;
887 if (i >= len) {
888 int status = PyList_Append(result, value);
889 Py_DECREF(value);
890 if (status < 0)
891 goto Fail_1;
893 else if (PyList_SetItem(result, i, value) < 0)
894 goto Fail_1;
897 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
898 goto Fail_1;
900 goto Succeed;
902 Fail_1:
903 Py_DECREF(result);
904 Fail_2:
905 result = NULL;
906 Succeed:
907 assert(seqs);
908 for (i = 0; i < n; ++i)
909 Py_XDECREF(seqs[i].it);
910 PyMem_DEL(seqs);
911 return result;
914 static char map_doc[] =
915 "map(function, sequence[, sequence, ...]) -> list\n\
917 Return a list of the results of applying the function to the items of\n\
918 the argument sequence(s). If more than one sequence is given, the\n\
919 function is called with an argument list consisting of the corresponding\n\
920 item of each sequence, substituting None for missing values when not all\n\
921 sequences have the same length. If the function is None, return a list of\n\
922 the items of the sequence (or a list of tuples if more than one sequence).";
925 static PyObject *
926 builtin_setattr(PyObject *self, PyObject *args)
928 PyObject *v;
929 PyObject *name;
930 PyObject *value;
932 if (!PyArg_ParseTuple(args, "OOO:setattr", &v, &name, &value))
933 return NULL;
934 if (PyObject_SetAttr(v, name, value) != 0)
935 return NULL;
936 Py_INCREF(Py_None);
937 return Py_None;
940 static char setattr_doc[] =
941 "setattr(object, name, value)\n\
943 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
944 ``x.y = v''.";
947 static PyObject *
948 builtin_delattr(PyObject *self, PyObject *args)
950 PyObject *v;
951 PyObject *name;
953 if (!PyArg_ParseTuple(args, "OO:delattr", &v, &name))
954 return NULL;
955 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
956 return NULL;
957 Py_INCREF(Py_None);
958 return Py_None;
961 static char delattr_doc[] =
962 "delattr(object, name)\n\
964 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
965 ``del x.y''.";
968 static PyObject *
969 builtin_hash(PyObject *self, PyObject *v)
971 long x;
973 x = PyObject_Hash(v);
974 if (x == -1)
975 return NULL;
976 return PyInt_FromLong(x);
979 static char hash_doc[] =
980 "hash(object) -> integer\n\
982 Return a hash value for the object. Two objects with the same value have\n\
983 the same hash value. The reverse is not necessarily true, but likely.";
986 static PyObject *
987 builtin_hex(PyObject *self, PyObject *v)
989 PyNumberMethods *nb;
991 if ((nb = v->ob_type->tp_as_number) == NULL ||
992 nb->nb_hex == NULL) {
993 PyErr_SetString(PyExc_TypeError,
994 "hex() argument can't be converted to hex");
995 return NULL;
997 return (*nb->nb_hex)(v);
1000 static char hex_doc[] =
1001 "hex(number) -> string\n\
1003 Return the hexadecimal representation of an integer or long integer.";
1006 static PyObject *builtin_raw_input(PyObject *, PyObject *);
1008 static PyObject *
1009 builtin_input(PyObject *self, PyObject *args)
1011 PyObject *line;
1012 char *str;
1013 PyObject *res;
1014 PyObject *globals, *locals;
1016 line = builtin_raw_input(self, args);
1017 if (line == NULL)
1018 return line;
1019 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1020 return NULL;
1021 while (*str == ' ' || *str == '\t')
1022 str++;
1023 globals = PyEval_GetGlobals();
1024 locals = PyEval_GetLocals();
1025 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1026 if (PyDict_SetItemString(globals, "__builtins__",
1027 PyEval_GetBuiltins()) != 0)
1028 return NULL;
1030 res = PyRun_String(str, Py_eval_input, globals, locals);
1031 Py_DECREF(line);
1032 return res;
1035 static char input_doc[] =
1036 "input([prompt]) -> value\n\
1038 Equivalent to eval(raw_input(prompt)).";
1041 static PyObject *
1042 builtin_intern(PyObject *self, PyObject *args)
1044 PyObject *s;
1045 if (!PyArg_ParseTuple(args, "S:intern", &s))
1046 return NULL;
1047 Py_INCREF(s);
1048 PyString_InternInPlace(&s);
1049 return s;
1052 static char intern_doc[] =
1053 "intern(string) -> string\n\
1055 ``Intern'' the given string. This enters the string in the (global)\n\
1056 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1057 Return the string itself or the previously interned string object with the\n\
1058 same value.";
1061 static PyObject *
1062 builtin_iter(PyObject *self, PyObject *args)
1064 PyObject *v, *w = NULL;
1066 if (!PyArg_ParseTuple(args, "O|O:iter", &v, &w))
1067 return NULL;
1068 if (w == NULL)
1069 return PyObject_GetIter(v);
1070 if (!PyCallable_Check(v)) {
1071 PyErr_SetString(PyExc_TypeError,
1072 "iter(v, w): v must be callable");
1073 return NULL;
1075 return PyCallIter_New(v, w);
1078 static char iter_doc[] =
1079 "iter(collection) -> iterator\n\
1080 iter(callable, sentinel) -> iterator\n\
1082 Get an iterator from an object. In the first form, the argument must\n\
1083 supply its own iterator, or be a sequence.\n\
1084 In the second form, the callable is called until it returns the sentinel.";
1087 static PyObject *
1088 builtin_len(PyObject *self, PyObject *v)
1090 long res;
1092 res = PyObject_Size(v);
1093 if (res < 0 && PyErr_Occurred())
1094 return NULL;
1095 return PyInt_FromLong(res);
1098 static char len_doc[] =
1099 "len(object) -> integer\n\
1101 Return the number of items of a sequence or mapping.";
1104 static PyObject *
1105 builtin_slice(PyObject *self, PyObject *args)
1107 PyObject *start, *stop, *step;
1109 start = stop = step = NULL;
1111 if (!PyArg_ParseTuple(args, "O|OO:slice", &start, &stop, &step))
1112 return NULL;
1114 /* This swapping of stop and start is to maintain similarity with
1115 range(). */
1116 if (stop == NULL) {
1117 stop = start;
1118 start = NULL;
1120 return PySlice_New(start, stop, step);
1123 static char slice_doc[] =
1124 "slice([start,] stop[, step]) -> slice object\n\
1126 Create a slice object. This is used for slicing by the Numeric extensions.";
1129 static PyObject *
1130 builtin_locals(PyObject *self)
1132 PyObject *d;
1134 d = PyEval_GetLocals();
1135 Py_INCREF(d);
1136 return d;
1139 static char locals_doc[] =
1140 "locals() -> dictionary\n\
1142 Return the dictionary containing the current scope's local variables.";
1145 static PyObject *
1146 min_max(PyObject *args, int op)
1148 PyObject *v, *w, *x, *it;
1150 if (PyTuple_Size(args) > 1)
1151 v = args;
1152 else if (!PyArg_ParseTuple(args, "O:min/max", &v))
1153 return NULL;
1155 it = PyObject_GetIter(v);
1156 if (it == NULL)
1157 return NULL;
1159 w = NULL; /* the result */
1160 for (;;) {
1161 x = PyIter_Next(it);
1162 if (x == NULL) {
1163 if (PyErr_Occurred()) {
1164 Py_XDECREF(w);
1165 Py_DECREF(it);
1166 return NULL;
1168 break;
1171 if (w == NULL)
1172 w = x;
1173 else {
1174 int cmp = PyObject_RichCompareBool(x, w, op);
1175 if (cmp > 0) {
1176 Py_DECREF(w);
1177 w = x;
1179 else if (cmp < 0) {
1180 Py_DECREF(x);
1181 Py_DECREF(w);
1182 Py_DECREF(it);
1183 return NULL;
1185 else
1186 Py_DECREF(x);
1189 if (w == NULL)
1190 PyErr_SetString(PyExc_ValueError,
1191 "min() or max() arg is an empty sequence");
1192 Py_DECREF(it);
1193 return w;
1196 static PyObject *
1197 builtin_min(PyObject *self, PyObject *v)
1199 return min_max(v, Py_LT);
1202 static char min_doc[] =
1203 "min(sequence) -> value\n\
1204 min(a, b, c, ...) -> value\n\
1206 With a single sequence argument, return its smallest item.\n\
1207 With two or more arguments, return the smallest argument.";
1210 static PyObject *
1211 builtin_max(PyObject *self, PyObject *v)
1213 return min_max(v, Py_GT);
1216 static char max_doc[] =
1217 "max(sequence) -> value\n\
1218 max(a, b, c, ...) -> value\n\
1220 With a single sequence argument, return its largest item.\n\
1221 With two or more arguments, return the largest argument.";
1224 static PyObject *
1225 builtin_oct(PyObject *self, PyObject *v)
1227 PyNumberMethods *nb;
1229 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1230 nb->nb_oct == NULL) {
1231 PyErr_SetString(PyExc_TypeError,
1232 "oct() argument can't be converted to oct");
1233 return NULL;
1235 return (*nb->nb_oct)(v);
1238 static char oct_doc[] =
1239 "oct(number) -> string\n\
1241 Return the octal representation of an integer or long integer.";
1244 static PyObject *
1245 builtin_open(PyObject *self, PyObject *args)
1247 char *name = NULL;
1248 char *mode = "r";
1249 int bufsize = -1;
1250 PyObject *f;
1252 if (!PyArg_ParseTuple(args, "et|si:open", Py_FileSystemDefaultEncoding,
1253 &name, &mode, &bufsize))
1254 return NULL;
1255 f = PyFile_FromString(name, mode);
1256 PyMem_Free(name); /* free the encoded string */
1257 if (f != NULL)
1258 PyFile_SetBufSize(f, bufsize);
1259 return f;
1262 static char open_doc[] =
1263 "open(filename[, mode[, buffering]]) -> file object\n\
1265 Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n\
1266 writing or appending. The file will be created if it doesn't exist\n\
1267 when opened for writing or appending; it will be truncated when\n\
1268 opened for writing. Add a 'b' to the mode for binary files.\n\
1269 Add a '+' to the mode to allow simultaneous reading and writing.\n\
1270 If the buffering argument is given, 0 means unbuffered, 1 means line\n\
1271 buffered, and larger numbers specify the buffer size.";
1274 static PyObject *
1275 builtin_ord(PyObject *self, PyObject* obj)
1277 long ord;
1278 int size;
1280 if (PyString_Check(obj)) {
1281 size = PyString_GET_SIZE(obj);
1282 if (size == 1) {
1283 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1284 return PyInt_FromLong(ord);
1286 #ifdef Py_USING_UNICODE
1287 } else if (PyUnicode_Check(obj)) {
1288 size = PyUnicode_GET_SIZE(obj);
1289 if (size == 1) {
1290 ord = (long)*PyUnicode_AS_UNICODE(obj);
1291 return PyInt_FromLong(ord);
1293 #endif
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 *v)
1616 return PyImport_ReloadModule(v);
1619 static char reload_doc[] =
1620 "reload(module) -> module\n\
1622 Reload the module. The module must have been successfully imported before.";
1625 static PyObject *
1626 builtin_repr(PyObject *self, PyObject *v)
1628 return PyObject_Repr(v);
1631 static char repr_doc[] =
1632 "repr(object) -> string\n\
1634 Return the canonical string representation of the object.\n\
1635 For most object types, eval(repr(object)) == object.";
1638 static PyObject *
1639 builtin_round(PyObject *self, PyObject *args)
1641 double x;
1642 double f;
1643 int ndigits = 0;
1644 int i;
1646 if (!PyArg_ParseTuple(args, "d|i:round", &x, &ndigits))
1647 return NULL;
1648 f = 1.0;
1649 i = abs(ndigits);
1650 while (--i >= 0)
1651 f = f*10.0;
1652 if (ndigits < 0)
1653 x /= f;
1654 else
1655 x *= f;
1656 if (x >= 0.0)
1657 x = floor(x + 0.5);
1658 else
1659 x = ceil(x - 0.5);
1660 if (ndigits < 0)
1661 x *= f;
1662 else
1663 x /= f;
1664 return PyFloat_FromDouble(x);
1667 static char round_doc[] =
1668 "round(number[, ndigits]) -> floating point number\n\
1670 Round a number to a given precision in decimal digits (default 0 digits).\n\
1671 This always returns a floating point number. Precision may be negative.";
1674 static PyObject *
1675 builtin_vars(PyObject *self, PyObject *args)
1677 PyObject *v = NULL;
1678 PyObject *d;
1680 if (!PyArg_ParseTuple(args, "|O:vars", &v))
1681 return NULL;
1682 if (v == NULL) {
1683 d = PyEval_GetLocals();
1684 if (d == NULL) {
1685 if (!PyErr_Occurred())
1686 PyErr_SetString(PyExc_SystemError,
1687 "no locals!?");
1689 else
1690 Py_INCREF(d);
1692 else {
1693 d = PyObject_GetAttrString(v, "__dict__");
1694 if (d == NULL) {
1695 PyErr_SetString(PyExc_TypeError,
1696 "vars() argument must have __dict__ attribute");
1697 return NULL;
1700 return d;
1703 static char vars_doc[] =
1704 "vars([object]) -> dictionary\n\
1706 Without arguments, equivalent to locals().\n\
1707 With an argument, equivalent to object.__dict__.";
1709 static PyObject *
1710 builtin_isinstance(PyObject *self, PyObject *args)
1712 PyObject *inst;
1713 PyObject *cls;
1714 int retval;
1716 if (!PyArg_ParseTuple(args, "OO:isinstance", &inst, &cls))
1717 return NULL;
1719 retval = PyObject_IsInstance(inst, cls);
1720 if (retval < 0)
1721 return NULL;
1722 return PyInt_FromLong(retval);
1725 static char isinstance_doc[] =
1726 "isinstance(object, class-or-type) -> Boolean\n\
1728 Return whether an object is an instance of a class or of a subclass thereof.\n\
1729 With a type as second argument, return whether that is the object's type.";
1732 static PyObject *
1733 builtin_issubclass(PyObject *self, PyObject *args)
1735 PyObject *derived;
1736 PyObject *cls;
1737 int retval;
1739 if (!PyArg_ParseTuple(args, "OO:issubclass", &derived, &cls))
1740 return NULL;
1742 retval = PyObject_IsSubclass(derived, cls);
1743 if (retval < 0)
1744 return NULL;
1745 return PyInt_FromLong(retval);
1748 static char issubclass_doc[] =
1749 "issubclass(C, B) -> Boolean\n\
1751 Return whether class C is a subclass (i.e., a derived class) of class B.";
1754 static PyObject*
1755 builtin_zip(PyObject *self, PyObject *args)
1757 PyObject *ret;
1758 int itemsize = PySequence_Length(args);
1759 int i;
1760 PyObject *itlist; /* tuple of iterators */
1762 if (itemsize < 1) {
1763 PyErr_SetString(PyExc_TypeError,
1764 "zip() requires at least one sequence");
1765 return NULL;
1767 /* args must be a tuple */
1768 assert(PyTuple_Check(args));
1770 /* allocate result list */
1771 if ((ret = PyList_New(0)) == NULL)
1772 return NULL;
1774 /* obtain iterators */
1775 itlist = PyTuple_New(itemsize);
1776 if (itlist == NULL)
1777 goto Fail_ret;
1778 for (i = 0; i < itemsize; ++i) {
1779 PyObject *item = PyTuple_GET_ITEM(args, i);
1780 PyObject *it = PyObject_GetIter(item);
1781 if (it == NULL) {
1782 if (PyErr_ExceptionMatches(PyExc_TypeError))
1783 PyErr_Format(PyExc_TypeError,
1784 "zip argument #%d must support iteration",
1785 i+1);
1786 goto Fail_ret_itlist;
1788 PyTuple_SET_ITEM(itlist, i, it);
1791 /* build result into ret list */
1792 for (;;) {
1793 int status;
1794 PyObject *next = PyTuple_New(itemsize);
1795 if (!next)
1796 goto Fail_ret_itlist;
1798 for (i = 0; i < itemsize; i++) {
1799 PyObject *it = PyTuple_GET_ITEM(itlist, i);
1800 PyObject *item = PyIter_Next(it);
1801 if (!item) {
1802 if (PyErr_Occurred()) {
1803 Py_DECREF(ret);
1804 ret = NULL;
1806 Py_DECREF(next);
1807 Py_DECREF(itlist);
1808 return ret;
1810 PyTuple_SET_ITEM(next, i, item);
1813 status = PyList_Append(ret, next);
1814 Py_DECREF(next);
1815 if (status < 0)
1816 goto Fail_ret_itlist;
1819 Fail_ret_itlist:
1820 Py_DECREF(itlist);
1821 Fail_ret:
1822 Py_DECREF(ret);
1823 return NULL;
1827 static char zip_doc[] =
1828 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
1830 Return a list of tuples, where each tuple contains the i-th element\n\
1831 from each of the argument sequences. The returned list is truncated\n\
1832 in length to the length of the shortest argument sequence.";
1835 static PyMethodDef builtin_methods[] = {
1836 {"__import__", builtin___import__, METH_VARARGS, import_doc},
1837 {"abs", builtin_abs, METH_O, abs_doc},
1838 {"apply", builtin_apply, METH_VARARGS, apply_doc},
1839 {"buffer", builtin_buffer, METH_VARARGS, buffer_doc},
1840 {"callable", builtin_callable, METH_O, callable_doc},
1841 {"chr", builtin_chr, METH_VARARGS, chr_doc},
1842 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
1843 {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
1844 {"compile", builtin_compile, METH_VARARGS, compile_doc},
1845 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
1846 {"dir", builtin_dir, METH_VARARGS, dir_doc},
1847 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
1848 {"eval", builtin_eval, METH_VARARGS, eval_doc},
1849 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
1850 {"filter", builtin_filter, METH_VARARGS, filter_doc},
1851 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
1852 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
1853 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
1854 {"hash", builtin_hash, METH_O, hash_doc},
1855 {"hex", builtin_hex, METH_O, hex_doc},
1856 {"id", builtin_id, METH_O, id_doc},
1857 {"input", builtin_input, METH_VARARGS, input_doc},
1858 {"intern", builtin_intern, METH_VARARGS, intern_doc},
1859 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
1860 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
1861 {"iter", builtin_iter, METH_VARARGS, iter_doc},
1862 {"len", builtin_len, METH_O, len_doc},
1863 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
1864 {"map", builtin_map, METH_VARARGS, map_doc},
1865 {"max", builtin_max, METH_VARARGS, max_doc},
1866 {"min", builtin_min, METH_VARARGS, min_doc},
1867 {"oct", builtin_oct, METH_O, oct_doc},
1868 {"open", builtin_open, METH_VARARGS, open_doc},
1869 {"ord", builtin_ord, METH_O, ord_doc},
1870 {"pow", builtin_pow, METH_VARARGS, pow_doc},
1871 {"range", builtin_range, METH_VARARGS, range_doc},
1872 {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
1873 {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
1874 {"reload", builtin_reload, METH_O, reload_doc},
1875 {"repr", builtin_repr, METH_O, repr_doc},
1876 {"round", builtin_round, METH_VARARGS, round_doc},
1877 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
1878 {"slice", builtin_slice, METH_VARARGS, slice_doc},
1879 #ifdef Py_USING_UNICODE
1880 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
1881 #endif
1882 {"vars", builtin_vars, METH_VARARGS, vars_doc},
1883 {"xrange", builtin_xrange, METH_VARARGS, xrange_doc},
1884 {"zip", builtin_zip, METH_VARARGS, zip_doc},
1885 {NULL, NULL},
1888 static char builtin_doc[] =
1889 "Built-in functions, exceptions, and other objects.\n\
1891 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.";
1893 PyObject *
1894 _PyBuiltin_Init(void)
1896 PyObject *mod, *dict, *debug;
1897 mod = Py_InitModule4("__builtin__", builtin_methods,
1898 builtin_doc, (PyObject *)NULL,
1899 PYTHON_API_VERSION);
1900 if (mod == NULL)
1901 return NULL;
1902 dict = PyModule_GetDict(mod);
1903 if (PyDict_SetItemString(dict, "None", Py_None) < 0)
1904 return NULL;
1905 if (PyDict_SetItemString(dict, "Ellipsis", Py_Ellipsis) < 0)
1906 return NULL;
1907 if (PyDict_SetItemString(dict, "NotImplemented",
1908 Py_NotImplemented) < 0)
1909 return NULL;
1910 if (PyDict_SetItemString(dict, "classmethod",
1911 (PyObject *) &PyClassMethod_Type) < 0)
1912 return NULL;
1913 #ifndef WITHOUT_COMPLEX
1914 if (PyDict_SetItemString(dict, "complex",
1915 (PyObject *) &PyComplex_Type) < 0)
1916 return NULL;
1917 #endif
1918 if (PyDict_SetItemString(dict, "dictionary",
1919 (PyObject *) &PyDict_Type) < 0)
1920 return NULL;
1921 if (PyDict_SetItemString(dict, "float",
1922 (PyObject *) &PyFloat_Type) < 0)
1923 return NULL;
1924 if (PyDict_SetItemString(dict, "int", (PyObject *) &PyInt_Type) < 0)
1925 return NULL;
1926 if (PyDict_SetItemString(dict, "list", (PyObject *) &PyList_Type) < 0)
1927 return NULL;
1928 if (PyDict_SetItemString(dict, "long", (PyObject *) &PyLong_Type) < 0)
1929 return NULL;
1930 if (PyDict_SetItemString(dict, "object",
1931 (PyObject *) &PyBaseObject_Type) < 0)
1932 return NULL;
1933 if (PyDict_SetItemString(dict, "staticmethod",
1934 (PyObject *) &PyStaticMethod_Type) < 0)
1935 return NULL;
1936 if (PyDict_SetItemString(dict, "str", (PyObject *) &PyString_Type) < 0)
1937 return NULL;
1938 if (PyDict_SetItemString(dict, "tuple",
1939 (PyObject *) &PyTuple_Type) < 0)
1940 return NULL;
1941 if (PyDict_SetItemString(dict, "type", (PyObject *) &PyType_Type) < 0)
1942 return NULL;
1943 #ifdef Py_USING_UNICODE
1944 if (PyDict_SetItemString(dict, "unicode",
1945 (PyObject *) &PyUnicode_Type) < 0)
1946 return NULL;
1947 #endif
1948 debug = PyInt_FromLong(Py_OptimizeFlag == 0);
1949 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
1950 Py_XDECREF(debug);
1951 return NULL;
1953 Py_XDECREF(debug);
1955 return mod;
1958 /* Helper for filter(): filter a tuple through a function */
1960 static PyObject *
1961 filtertuple(PyObject *func, PyObject *tuple)
1963 PyObject *result;
1964 register int i, j;
1965 int len = PyTuple_Size(tuple);
1967 if (len == 0) {
1968 Py_INCREF(tuple);
1969 return tuple;
1972 if ((result = PyTuple_New(len)) == NULL)
1973 return NULL;
1975 for (i = j = 0; i < len; ++i) {
1976 PyObject *item, *good;
1977 int ok;
1979 if ((item = PyTuple_GetItem(tuple, i)) == NULL)
1980 goto Fail_1;
1981 if (func == Py_None) {
1982 Py_INCREF(item);
1983 good = item;
1985 else {
1986 PyObject *arg = Py_BuildValue("(O)", item);
1987 if (arg == NULL)
1988 goto Fail_1;
1989 good = PyEval_CallObject(func, arg);
1990 Py_DECREF(arg);
1991 if (good == NULL)
1992 goto Fail_1;
1994 ok = PyObject_IsTrue(good);
1995 Py_DECREF(good);
1996 if (ok) {
1997 Py_INCREF(item);
1998 if (PyTuple_SetItem(result, j++, item) < 0)
1999 goto Fail_1;
2003 if (_PyTuple_Resize(&result, j) < 0)
2004 return NULL;
2006 return result;
2008 Fail_1:
2009 Py_DECREF(result);
2010 return NULL;
2014 /* Helper for filter(): filter a string through a function */
2016 static PyObject *
2017 filterstring(PyObject *func, PyObject *strobj)
2019 PyObject *result;
2020 register int i, j;
2021 int len = PyString_Size(strobj);
2023 if (func == Py_None) {
2024 /* No character is ever false -- share input string */
2025 Py_INCREF(strobj);
2026 return strobj;
2028 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2029 return NULL;
2031 for (i = j = 0; i < len; ++i) {
2032 PyObject *item, *arg, *good;
2033 int ok;
2035 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2036 if (item == NULL)
2037 goto Fail_1;
2038 arg = Py_BuildValue("(O)", item);
2039 if (arg == NULL) {
2040 Py_DECREF(item);
2041 goto Fail_1;
2043 good = PyEval_CallObject(func, arg);
2044 Py_DECREF(arg);
2045 if (good == NULL) {
2046 Py_DECREF(item);
2047 goto Fail_1;
2049 ok = PyObject_IsTrue(good);
2050 Py_DECREF(good);
2051 if (ok)
2052 PyString_AS_STRING((PyStringObject *)result)[j++] =
2053 PyString_AS_STRING((PyStringObject *)item)[0];
2054 Py_DECREF(item);
2057 if (j < len && _PyString_Resize(&result, j) < 0)
2058 return NULL;
2060 return result;
2062 Fail_1:
2063 Py_DECREF(result);
2064 return NULL;