Added all documentation.
[python/dscho.git] / Python / bltinmodule.c
blob9bb8784b0fdeaedaa510ea06002fcbb7a3f0c156
1 /***********************************************************
2 Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
3 The Netherlands.
5 All Rights Reserved
7 Permission to use, copy, modify, and distribute this software and its
8 documentation for any purpose and without fee is hereby granted,
9 provided that the above copyright notice appear in all copies and that
10 both that copyright notice and this permission notice appear in
11 supporting documentation, and that the names of Stichting Mathematisch
12 Centrum or CWI or Corporation for National Research Initiatives or
13 CNRI not be used in advertising or publicity pertaining to
14 distribution of the software without specific, written prior
15 permission.
17 While CWI is the initial source for this software, a modified version
18 is made available by the Corporation for National Research Initiatives
19 (CNRI) at the Internet address ftp://ftp.python.org.
21 STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
22 REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
23 MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
24 CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
25 DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
26 PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
27 TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28 PERFORMANCE OF THIS SOFTWARE.
30 ******************************************************************/
32 /* Built-in functions */
34 #include "Python.h"
36 #include "node.h"
37 #include "compile.h"
38 #include "eval.h"
40 #include "mymath.h"
42 #include <ctype.h>
44 #ifdef HAVE_UNISTD_H
45 #include <unistd.h>
46 #endif
48 /* Forward */
49 static PyObject *filterstring Py_PROTO((PyObject *, PyObject *));
50 static PyObject *filtertuple Py_PROTO((PyObject *, PyObject *));
52 static PyObject *
53 builtin___import__(self, args)
54 PyObject *self;
55 PyObject *args;
57 char *name;
58 PyObject *globals = NULL;
59 PyObject *locals = NULL;
60 PyObject *fromlist = NULL;
62 if (!PyArg_ParseTuple(args, "s|OOO:__import__",
63 &name, &globals, &locals, &fromlist))
64 return NULL;
65 return PyImport_ImportModuleEx(name, globals, locals, fromlist);
68 static char import_doc[] =
69 "__import__(name, globals, locals, fromlist) -> module\n\
70 \n\
71 Import a module. The globals are only used to determine the context;\n\
72 they are not modified. The locals are currently unused. The fromlist\n\
73 should be a list of names to emulate ``from name import ...'', or an\n\
74 empty list to emulate ``import name''.\n\
75 When importing a module from a package, note that __import__('A.B', ...)\n\
76 returns package A when fromlist is empty, but its submodule B when\n\
77 fromlist is not empty.";
80 static PyObject *
81 builtin_abs(self, args)
82 PyObject *self;
83 PyObject *args;
85 PyObject *v;
87 if (!PyArg_ParseTuple(args, "O:abs", &v))
88 return NULL;
89 return PyNumber_Absolute(v);
92 static char abs_doc[] =
93 "abs(number) -> number\n\
94 \n\
95 Return the absolute value of the argument.";
98 static PyObject *
99 builtin_apply(self, args)
100 PyObject *self;
101 PyObject *args;
103 PyObject *func, *alist = NULL, *kwdict = NULL;
104 PyObject *t = NULL, *retval = NULL;
106 if (!PyArg_ParseTuple(args, "O|OO:apply", &func, &alist, &kwdict))
107 return NULL;
108 if (alist != NULL) {
109 if (!PyTuple_Check(alist)) {
110 if (!PySequence_Check(alist)) {
111 PyErr_SetString(PyExc_TypeError,
112 "apply() 2nd argument must be a sequence");
113 return NULL;
115 t = PySequence_Tuple(alist);
116 if (t == NULL)
117 return NULL;
118 alist = t;
121 if (kwdict != NULL && !PyDict_Check(kwdict)) {
122 PyErr_SetString(PyExc_TypeError,
123 "apply() 3rd argument must be dictionary");
124 goto finally;
126 retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
127 finally:
128 Py_XDECREF(t);
129 return retval;
132 static char apply_doc[] =
133 "apply(function, args[, kwargs]) -> value\n\
135 Call a function with positional arguments taken from the tuple args,\n\
136 and keyword arguments taken from the optional dictionary kwargs.";
139 static PyObject *
140 builtin_buffer(self, args)
141 PyObject *self;
142 PyObject *args;
144 PyObject *ob;
145 int offset = 0;
146 int size = Py_END_OF_BUFFER;
148 if ( !PyArg_ParseTuple(args, "O|ii:buffer", &ob, &offset, &size) )
149 return NULL;
150 return PyBuffer_FromObject(ob, offset, size);
153 static char buffer_doc[] =
154 "buffer(object [, offset[, size]) -> object\n\
156 Creates a new buffer object which references the given object.\n\
157 The buffer will reference a slice of the target object from the\n\
158 start of the object (or at the specified offset). The slice will\n\
159 extend to the end of the target object (or with the specified size).";
162 static PyObject *
163 builtin_callable(self, args)
164 PyObject *self;
165 PyObject *args;
167 PyObject *v;
169 if (!PyArg_ParseTuple(args, "O:callable", &v))
170 return NULL;
171 return PyInt_FromLong((long)PyCallable_Check(v));
174 static char callable_doc[] =
175 "callable(object) -> Boolean\n\
177 Return whether the object is callable (i.e., some kind of function).\n\
178 Note that classes are callable, as are instances with a __call__() method.";
181 static PyObject *
182 builtin_filter(self, args)
183 PyObject *self;
184 PyObject *args;
186 PyObject *func, *seq, *result;
187 PySequenceMethods *sqf;
188 int len;
189 register int i, j;
191 if (!PyArg_ParseTuple(args, "OO:filter", &func, &seq))
192 return NULL;
194 if (PyString_Check(seq)) {
195 PyObject *r = filterstring(func, seq);
196 return r;
199 if (PyTuple_Check(seq)) {
200 PyObject *r = filtertuple(func, seq);
201 return r;
204 sqf = seq->ob_type->tp_as_sequence;
205 if (sqf == NULL || sqf->sq_length == NULL || sqf->sq_item == NULL) {
206 PyErr_SetString(PyExc_TypeError,
207 "argument 2 to filter() must be a sequence type");
208 goto Fail_2;
211 if ((len = (*sqf->sq_length)(seq)) < 0)
212 goto Fail_2;
214 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
215 Py_INCREF(seq);
216 result = seq;
218 else {
219 if ((result = PyList_New(len)) == NULL)
220 goto Fail_2;
223 for (i = j = 0; ; ++i) {
224 PyObject *item, *good;
225 int ok;
227 if ((item = (*sqf->sq_item)(seq, i)) == NULL) {
228 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
229 PyErr_Clear();
230 break;
232 goto Fail_1;
235 if (func == Py_None) {
236 good = item;
237 Py_INCREF(good);
239 else {
240 PyObject *arg = Py_BuildValue("(O)", item);
241 if (arg == NULL)
242 goto Fail_1;
243 good = PyEval_CallObject(func, arg);
244 Py_DECREF(arg);
245 if (good == NULL) {
246 Py_DECREF(item);
247 goto Fail_1;
250 ok = PyObject_IsTrue(good);
251 Py_DECREF(good);
252 if (ok) {
253 if (j < len) {
254 if (PyList_SetItem(result, j++, item) < 0)
255 goto Fail_1;
257 else {
258 int status = PyList_Append(result, item);
259 j++;
260 Py_DECREF(item);
261 if (status < 0)
262 goto Fail_1;
264 } else {
265 Py_DECREF(item);
270 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
271 goto Fail_1;
273 return result;
275 Fail_1:
276 Py_DECREF(result);
277 Fail_2:
278 return NULL;
281 static char filter_doc[] =
282 "filter(function, sequence) -> list\n\
284 Return a list containing those items of sequence for which function(item)\n\
285 is true. If function is None, return a list of items that are true.";
288 static PyObject *
289 builtin_chr(self, args)
290 PyObject *self;
291 PyObject *args;
293 long x;
294 char s[1];
296 if (!PyArg_ParseTuple(args, "l:chr", &x))
297 return NULL;
298 if (x < 0 || x >= 256) {
299 PyErr_SetString(PyExc_ValueError,
300 "chr() arg not in range(256)");
301 return NULL;
303 s[0] = (char)x;
304 return PyString_FromStringAndSize(s, 1);
307 static char chr_doc[] =
308 "chr(i) -> character\n\
310 Return a string of one character with ordinal i; 0 <= i < 256.";
313 static PyObject *
314 builtin_cmp(self, args)
315 PyObject *self;
316 PyObject *args;
318 PyObject *a, *b;
319 int c;
321 if (!PyArg_ParseTuple(args, "OO:cmp", &a, &b))
322 return NULL;
323 if (PyObject_Cmp(a, b, &c) < 0)
324 return NULL;
325 return PyInt_FromLong((long)c);
328 static char cmp_doc[] =
329 "cmp(x, y) -> integer\n\
331 Return negative if x<y, zero if x==y, positive if x>y.";
334 static PyObject *
335 builtin_coerce(self, args)
336 PyObject *self;
337 PyObject *args;
339 PyObject *v, *w;
340 PyObject *res;
342 if (!PyArg_ParseTuple(args, "OO:coerce", &v, &w))
343 return NULL;
344 if (PyNumber_Coerce(&v, &w) < 0)
345 return NULL;
346 res = Py_BuildValue("(OO)", v, w);
347 Py_DECREF(v);
348 Py_DECREF(w);
349 return res;
352 static char coerce_doc[] =
353 "coerce(x, y) -> None or (x1, y1)\n\
355 When x and y can be coerced to values of the same type, return a tuple\n\
356 containing the coerced values. When they can't be coerced, return None.";
359 static PyObject *
360 builtin_compile(self, args)
361 PyObject *self;
362 PyObject *args;
364 char *str;
365 char *filename;
366 char *startstr;
367 int start;
369 if (!PyArg_ParseTuple(args, "sss:compile", &str, &filename, &startstr))
370 return NULL;
371 if (strcmp(startstr, "exec") == 0)
372 start = Py_file_input;
373 else if (strcmp(startstr, "eval") == 0)
374 start = Py_eval_input;
375 else if (strcmp(startstr, "single") == 0)
376 start = Py_single_input;
377 else {
378 PyErr_SetString(PyExc_ValueError,
379 "compile() mode must be 'exec' or 'eval' or 'single'");
380 return NULL;
382 return Py_CompileString(str, filename, start);
385 static char compile_doc[] =
386 "compile(source, filename, mode) -> code object\n\
388 Compile the source string (a Python module, statement or expression)\n\
389 into a code object that can be executed by the exec statement or eval().\n\
390 The filename will be used for run-time error messages.\n\
391 The mode must be 'exec' to compile a module, 'single' to compile a\n\
392 single (interactive) statement, or 'eval' to compile an expression.";
395 #ifndef WITHOUT_COMPLEX
397 static PyObject *
398 complex_from_string(v)
399 PyObject *v;
401 extern double strtod Py_PROTO((const char *, char **));
402 char *s, *start, *end;
403 double x=0.0, y=0.0, z;
404 int got_re=0, got_im=0, done=0;
405 int digit_or_dot;
406 int sw_error=0;
407 int sign;
408 char buffer[256]; /* For errors */
410 start = s = PyString_AS_STRING(v);
412 /* position on first nonblank */
413 while (*s && isspace(Py_CHARMASK(*s)))
414 s++;
415 if (s[0] == '\0') {
416 PyErr_SetString(PyExc_ValueError,
417 "empty string for complex()");
418 return NULL;
421 z = -1.0;
422 sign = 1;
423 do {
425 switch (*s) {
427 case '\0':
428 if (s-start != PyString_GET_SIZE(v)) {
429 PyErr_SetString(
430 PyExc_ValueError,
431 "null byte in argument for complex()");
432 return NULL;
434 if(!done) sw_error=1;
435 break;
437 case '-':
438 sign = -1;
439 /* Fallthrough */
440 case '+':
441 if (done) sw_error=1;
442 s++;
443 if ( *s=='\0'||*s=='+'||*s=='-' ||
444 isspace(Py_CHARMASK(*s)) ) sw_error=1;
445 break;
447 case 'J':
448 case 'j':
449 if (got_im || done) {
450 sw_error = 1;
451 break;
453 if (z<0.0) {
454 y=sign;
456 else{
457 y=sign*z;
459 got_im=1;
460 s++;
461 if (*s!='+' && *s!='-' )
462 done=1;
463 break;
465 default:
466 if (isspace(Py_CHARMASK(*s))) {
467 while (*s && isspace(Py_CHARMASK(*s)))
468 s++;
469 if (s[0] != '\0')
470 sw_error=1;
471 else
472 done = 1;
473 break;
475 digit_or_dot =
476 (*s=='.' || isdigit(Py_CHARMASK(*s)));
477 if (done||!digit_or_dot) {
478 sw_error=1;
479 break;
481 errno = 0;
482 PyFPE_START_PROTECT("strtod", return 0)
483 z = strtod(s, &end) ;
484 PyFPE_END_PROTECT(z)
485 if (errno != 0) {
486 sprintf(buffer,
487 "float() out of range: %.150s", s);
488 PyErr_SetString(
489 PyExc_ValueError,
490 buffer);
491 return NULL;
493 s=end;
494 if (*s=='J' || *s=='j') {
496 break;
498 if (got_re) {
499 sw_error=1;
500 break;
503 /* accept a real part */
504 x=sign*z;
505 got_re=1;
506 if (got_im) done=1;
507 z = -1.0;
508 sign = 1;
509 break;
511 } /* end of switch */
513 } while (*s!='\0' && !sw_error);
515 if (sw_error) {
516 PyErr_SetString(PyExc_ValueError,
517 "malformed string for complex()");
518 return NULL;
521 return PyComplex_FromDoubles(x,y);
524 static PyObject *
525 builtin_complex(self, args)
526 PyObject *self;
527 PyObject *args;
529 PyObject *r, *i, *tmp;
530 PyNumberMethods *nbr, *nbi = NULL;
531 Py_complex cr, ci;
532 int own_r = 0;
534 i = NULL;
535 if (!PyArg_ParseTuple(args, "O|O:complex", &r, &i))
536 return NULL;
537 if (PyString_Check(r))
538 return complex_from_string(r);
539 if ((nbr = r->ob_type->tp_as_number) == NULL ||
540 nbr->nb_float == NULL ||
541 (i != NULL &&
542 ((nbi = i->ob_type->tp_as_number) == NULL ||
543 nbi->nb_float == NULL))) {
544 PyErr_SetString(PyExc_TypeError,
545 "complex() argument can't be converted to complex");
546 return NULL;
548 /* XXX Hack to support classes with __complex__ method */
549 if (PyInstance_Check(r)) {
550 static PyObject *complexstr;
551 PyObject *f;
552 if (complexstr == NULL) {
553 complexstr = PyString_InternFromString("__complex__");
554 if (complexstr == NULL)
555 return NULL;
557 f = PyObject_GetAttr(r, complexstr);
558 if (f == NULL)
559 PyErr_Clear();
560 else {
561 PyObject *args = Py_BuildValue("()");
562 if (args == NULL)
563 return NULL;
564 r = PyEval_CallObject(f, args);
565 Py_DECREF(args);
566 Py_DECREF(f);
567 if (r == NULL)
568 return NULL;
569 own_r = 1;
572 if (PyComplex_Check(r)) {
573 cr = ((PyComplexObject*)r)->cval;
574 if (own_r) {
575 Py_DECREF(r);
578 else {
579 tmp = (*nbr->nb_float)(r);
580 if (own_r) {
581 Py_DECREF(r);
583 if (tmp == NULL)
584 return NULL;
585 cr.real = PyFloat_AsDouble(tmp);
586 Py_DECREF(tmp);
587 cr.imag = 0.0;
589 if (i == NULL) {
590 ci.real = 0.0;
591 ci.imag = 0.0;
593 else if (PyComplex_Check(i))
594 ci = ((PyComplexObject*)i)->cval;
595 else {
596 tmp = (*nbi->nb_float)(i);
597 if (tmp == NULL)
598 return NULL;
599 ci.real = PyFloat_AsDouble(tmp);
600 Py_DECREF(tmp);
601 ci.imag = 0.;
603 cr.real -= ci.imag;
604 cr.imag += ci.real;
605 return PyComplex_FromCComplex(cr);
608 static char complex_doc[] =
609 "complex(real[, imag]) -> complex number\n\
611 Create a complex number from a real part and an optional imaginary part.\n\
612 This is equivalent to (real + imag*1j) where imag defaults to 0.";
615 #endif
617 static PyObject *
618 builtin_dir(self, args)
619 PyObject *self;
620 PyObject *args;
622 static char *attrlist[] = {"__members__", "__methods__", NULL};
623 PyObject *v = NULL, *l = NULL, *m = NULL;
624 PyObject *d, *x;
625 int i;
626 char **s;
628 if (!PyArg_ParseTuple(args, "|O:dir", &v))
629 return NULL;
630 if (v == NULL) {
631 x = PyEval_GetLocals();
632 if (x == NULL)
633 goto error;
634 l = PyMapping_Keys(x);
635 if (l == NULL)
636 goto error;
638 else {
639 d = PyObject_GetAttrString(v, "__dict__");
640 if (d == NULL)
641 PyErr_Clear();
642 else {
643 l = PyMapping_Keys(d);
644 if (l == NULL)
645 PyErr_Clear();
646 Py_DECREF(d);
648 if (l == NULL) {
649 l = PyList_New(0);
650 if (l == NULL)
651 goto error;
653 for (s = attrlist; *s != NULL; s++) {
654 m = PyObject_GetAttrString(v, *s);
655 if (m == NULL) {
656 PyErr_Clear();
657 continue;
659 for (i = 0; ; i++) {
660 x = PySequence_GetItem(m, i);
661 if (x == NULL) {
662 PyErr_Clear();
663 break;
665 if (PyList_Append(l, x) != 0) {
666 Py_DECREF(x);
667 Py_DECREF(m);
668 goto error;
670 Py_DECREF(x);
672 Py_DECREF(m);
675 if (PyList_Sort(l) != 0)
676 goto error;
677 return l;
678 error:
679 Py_XDECREF(l);
680 return NULL;
683 static char dir_doc[] =
684 "dir([object]) -> list of strings\n\
686 Return an alphabetized list of names comprising (some of) the attributes\n\
687 of the given object. Without an argument, the names in the current scope\n\
688 are listed. With an instance argument, only the instance attributes are\n\
689 returned. With a class argument, attributes of the base class are not\n\
690 returned. For other types or arguments, this may list members or methods.";
693 static PyObject *
694 builtin_divmod(self, args)
695 PyObject *self;
696 PyObject *args;
698 PyObject *v, *w;
700 if (!PyArg_ParseTuple(args, "OO:divmod", &v, &w))
701 return NULL;
702 return PyNumber_Divmod(v, w);
705 static char divmod_doc[] =
706 "divmod(x, y) -> (div, mod)\n\
708 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.";
711 static PyObject *
712 builtin_eval(self, args)
713 PyObject *self;
714 PyObject *args;
716 PyObject *cmd;
717 PyObject *globals = Py_None, *locals = Py_None;
718 char *str;
720 if (!PyArg_ParseTuple(args, "O|O!O!:eval",
721 &cmd,
722 &PyDict_Type, &globals,
723 &PyDict_Type, &locals))
724 return NULL;
725 if (globals == Py_None) {
726 globals = PyEval_GetGlobals();
727 if (locals == Py_None)
728 locals = PyEval_GetLocals();
730 else if (locals == Py_None)
731 locals = globals;
732 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
733 if (PyDict_SetItemString(globals, "__builtins__",
734 PyEval_GetBuiltins()) != 0)
735 return NULL;
737 if (PyCode_Check(cmd))
738 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
739 if (!PyString_Check(cmd)) {
740 PyErr_SetString(PyExc_TypeError,
741 "eval() argument 1 must be string or code object");
742 return NULL;
744 str = PyString_AsString(cmd);
745 if ((int)strlen(str) != PyString_Size(cmd)) {
746 PyErr_SetString(PyExc_ValueError,
747 "embedded '\\0' in string arg");
748 return NULL;
750 while (*str == ' ' || *str == '\t')
751 str++;
752 return PyRun_String(str, Py_eval_input, globals, locals);
755 static char eval_doc[] =
756 "eval(source[, globals[, locals]]) -> value\n\
758 Evaluate the source in the context of globals and locals.\n\
759 The source may be a string representing a Python expression\n\
760 or a code object as returned by compile().\n\
761 The globals and locals are dictionaries, defaulting to the current\n\
762 globals and locals. If only globals is given, locals defaults to it.";
765 static PyObject *
766 builtin_execfile(self, args)
767 PyObject *self;
768 PyObject *args;
770 char *filename;
771 PyObject *globals = Py_None, *locals = Py_None;
772 PyObject *res;
773 FILE* fp;
775 if (!PyArg_ParseTuple(args, "s|O!O!:execfile",
776 &filename,
777 &PyDict_Type, &globals,
778 &PyDict_Type, &locals))
779 return NULL;
780 if (globals == Py_None) {
781 globals = PyEval_GetGlobals();
782 if (locals == Py_None)
783 locals = PyEval_GetLocals();
785 else if (locals == Py_None)
786 locals = globals;
787 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
788 if (PyDict_SetItemString(globals, "__builtins__",
789 PyEval_GetBuiltins()) != 0)
790 return NULL;
792 Py_BEGIN_ALLOW_THREADS
793 fp = fopen(filename, "r");
794 Py_END_ALLOW_THREADS
795 if (fp == NULL) {
796 PyErr_SetFromErrno(PyExc_IOError);
797 return NULL;
799 res = PyRun_File(fp, filename, Py_file_input, globals, locals);
800 Py_BEGIN_ALLOW_THREADS
801 fclose(fp);
802 Py_END_ALLOW_THREADS
803 return res;
806 static char execfile_doc[] =
807 "execfile(filename[, globals[, locals]])\n\
809 Read and execute a Python script from a file.\n\
810 The globals and locals are dictionaries, defaulting to the current\n\
811 globals and locals. If only globals is given, locals defaults to it.";
814 static PyObject *
815 builtin_float(self, args)
816 PyObject *self;
817 PyObject *args;
819 PyObject *v;
821 if (!PyArg_ParseTuple(args, "O:float", &v))
822 return NULL;
823 return PyNumber_Float(v);
826 static char float_doc[] =
827 "float(x) -> floating point number\n\
829 Convert a string or number to a floating point number, if possible.";
832 static PyObject *
833 builtin_getattr(self, args)
834 PyObject *self;
835 PyObject *args;
837 PyObject *v, *result, *dflt = NULL;
838 PyObject *name;
840 if (!PyArg_ParseTuple(args, "OS|O:getattr", &v, &name, &dflt))
841 return NULL;
842 result = PyObject_GetAttr(v, name);
843 if (result == NULL && dflt != NULL) {
844 PyErr_Clear();
845 Py_INCREF(dflt);
846 result = dflt;
848 return result;
851 static char getattr_doc[] =
852 "getattr(object, name[, default]) -> value\n\
854 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
855 When a default argument is given, it is returned when the attribute doesn't\n\
856 exist; without it, an exception is raised in that case.";
859 static PyObject *
860 builtin_globals(self, args)
861 PyObject *self;
862 PyObject *args;
864 PyObject *d;
866 if (!PyArg_ParseTuple(args, ""))
867 return NULL;
868 d = PyEval_GetGlobals();
869 Py_INCREF(d);
870 return d;
873 static char globals_doc[] =
874 "globals() -> dictionary\n\
876 Return the dictionary containing the current scope's global variables.";
879 static PyObject *
880 builtin_hasattr(self, args)
881 PyObject *self;
882 PyObject *args;
884 PyObject *v;
885 PyObject *name;
887 if (!PyArg_ParseTuple(args, "OS:hasattr", &v, &name))
888 return NULL;
889 v = PyObject_GetAttr(v, name);
890 if (v == NULL) {
891 PyErr_Clear();
892 Py_INCREF(Py_False);
893 return Py_False;
895 Py_DECREF(v);
896 Py_INCREF(Py_True);
897 return Py_True;
900 static char hasattr_doc[] =
901 "hasattr(object, name) -> Boolean\n\
903 Return whether the object has an attribute with the given name.\n\
904 (This is done by calling getattr(object, name) and catching exceptions.)";
907 static PyObject *
908 builtin_id(self, args)
909 PyObject *self;
910 PyObject *args;
912 PyObject *v;
914 if (!PyArg_ParseTuple(args, "O:id", &v))
915 return NULL;
916 return PyInt_FromLong((long)v);
919 static char id_doc[] =
920 "id(object) -> integer\n\
922 Return the identity of an object. This is guaranteed to be unique among\n\
923 simultaneously existing objects. (Hint: it's the object's memory address.)";
926 static PyObject *
927 builtin_map(self, args)
928 PyObject *self;
929 PyObject *args;
931 typedef struct {
932 PyObject *seq;
933 PySequenceMethods *sqf;
934 int len;
935 } sequence;
937 PyObject *func, *result;
938 sequence *seqs = NULL, *sqp;
939 int n, len;
940 register int i, j;
942 n = PyTuple_Size(args);
943 if (n < 2) {
944 PyErr_SetString(PyExc_TypeError,
945 "map() requires at least two args");
946 return NULL;
949 func = PyTuple_GetItem(args, 0);
950 n--;
952 if (func == Py_None && n == 1) {
953 /* map(None, S) is the same as list(S). */
954 return PySequence_List(PyTuple_GetItem(args, 1));
957 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
958 PyErr_NoMemory();
959 goto Fail_2;
962 for (len = 0, i = 0, sqp = seqs; i < n; ++i, ++sqp) {
963 int curlen;
964 PySequenceMethods *sqf;
966 if ((sqp->seq = PyTuple_GetItem(args, i + 1)) == NULL)
967 goto Fail_2;
969 sqp->sqf = sqf = sqp->seq->ob_type->tp_as_sequence;
970 if (sqf == NULL ||
971 sqf->sq_length == NULL ||
972 sqf->sq_item == NULL)
974 static char errmsg[] =
975 "argument %d to map() must be a sequence object";
976 char errbuf[sizeof(errmsg) + 25];
978 sprintf(errbuf, errmsg, i+2);
979 PyErr_SetString(PyExc_TypeError, errbuf);
980 goto Fail_2;
983 if ((curlen = sqp->len = (*sqp->sqf->sq_length)(sqp->seq)) < 0)
984 goto Fail_2;
986 if (curlen > len)
987 len = curlen;
990 if ((result = (PyObject *) PyList_New(len)) == NULL)
991 goto Fail_2;
993 for (i = 0; ; ++i) {
994 PyObject *alist, *item=NULL, *value;
995 int any = 0;
997 if (func == Py_None && n == 1)
998 alist = NULL;
999 else {
1000 if ((alist = PyTuple_New(n)) == NULL)
1001 goto Fail_1;
1004 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
1005 if (sqp->len < 0) {
1006 Py_INCREF(Py_None);
1007 item = Py_None;
1009 else {
1010 item = (*sqp->sqf->sq_item)(sqp->seq, i);
1011 if (item == NULL) {
1012 if (PyErr_ExceptionMatches(
1013 PyExc_IndexError))
1015 PyErr_Clear();
1016 Py_INCREF(Py_None);
1017 item = Py_None;
1018 sqp->len = -1;
1020 else {
1021 goto Fail_0;
1024 else
1025 any = 1;
1028 if (!alist)
1029 break;
1030 if (PyTuple_SetItem(alist, j, item) < 0) {
1031 Py_DECREF(item);
1032 goto Fail_0;
1034 continue;
1036 Fail_0:
1037 Py_XDECREF(alist);
1038 goto Fail_1;
1041 if (!alist)
1042 alist = item;
1044 if (!any) {
1045 Py_DECREF(alist);
1046 break;
1049 if (func == Py_None)
1050 value = alist;
1051 else {
1052 value = PyEval_CallObject(func, alist);
1053 Py_DECREF(alist);
1054 if (value == NULL)
1055 goto Fail_1;
1057 if (i >= len) {
1058 int status = PyList_Append(result, value);
1059 Py_DECREF(value);
1060 if (status < 0)
1061 goto Fail_1;
1063 else {
1064 if (PyList_SetItem(result, i, value) < 0)
1065 goto Fail_1;
1069 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
1070 goto Fail_1;
1072 PyMem_DEL(seqs);
1073 return result;
1075 Fail_1:
1076 Py_DECREF(result);
1077 Fail_2:
1078 if (seqs) PyMem_DEL(seqs);
1079 return NULL;
1082 static char map_doc[] =
1083 "map(function, sequence[, sequence, ...]) -> list\n\
1085 Return a list of the results of applying the function to the items of\n\
1086 the argument sequence(s). If more than one sequence is given, the\n\
1087 function is called with an argument list consisting of the corresponding\n\
1088 item of each sequence, substituting None for missing values when not all\n\
1089 sequences have the same length. If the function is None, return a list of\n\
1090 the items of the sequence (or a list of tuples if more than one sequence).";
1093 static PyObject *
1094 builtin_setattr(self, args)
1095 PyObject *self;
1096 PyObject *args;
1098 PyObject *v;
1099 PyObject *name;
1100 PyObject *value;
1102 if (!PyArg_ParseTuple(args, "OSO:setattr", &v, &name, &value))
1103 return NULL;
1104 if (PyObject_SetAttr(v, name, value) != 0)
1105 return NULL;
1106 Py_INCREF(Py_None);
1107 return Py_None;
1110 static char setattr_doc[] =
1111 "setattr(object, name, value)\n\
1113 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1114 ``x.y = v''.";
1117 static PyObject *
1118 builtin_delattr(self, args)
1119 PyObject *self;
1120 PyObject *args;
1122 PyObject *v;
1123 PyObject *name;
1125 if (!PyArg_ParseTuple(args, "OS:delattr", &v, &name))
1126 return NULL;
1127 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1128 return NULL;
1129 Py_INCREF(Py_None);
1130 return Py_None;
1133 static char delattr_doc[] =
1134 "delattr(object, name)\n\
1136 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1137 ``del x.y''.";
1140 static PyObject *
1141 builtin_hash(self, args)
1142 PyObject *self;
1143 PyObject *args;
1145 PyObject *v;
1146 long x;
1148 if (!PyArg_ParseTuple(args, "O:hash", &v))
1149 return NULL;
1150 x = PyObject_Hash(v);
1151 if (x == -1)
1152 return NULL;
1153 return PyInt_FromLong(x);
1156 static char hash_doc[] =
1157 "hash(object) -> integer\n\
1159 Return a hash value for the object. Two objects with the same value have\n\
1160 the same hash value. The reverse is not necessarily true, but likely.";
1163 static PyObject *
1164 builtin_hex(self, args)
1165 PyObject *self;
1166 PyObject *args;
1168 PyObject *v;
1169 PyNumberMethods *nb;
1171 if (!PyArg_ParseTuple(args, "O:hex", &v))
1172 return NULL;
1174 if ((nb = v->ob_type->tp_as_number) == NULL ||
1175 nb->nb_hex == NULL) {
1176 PyErr_SetString(PyExc_TypeError,
1177 "hex() argument can't be converted to hex");
1178 return NULL;
1180 return (*nb->nb_hex)(v);
1183 static char hex_doc[] =
1184 "hex(number) -> string\n\
1186 Return the hexadecimal representation of an integer or long integer.";
1189 static PyObject *builtin_raw_input Py_PROTO((PyObject *, PyObject *));
1191 static PyObject *
1192 builtin_input(self, args)
1193 PyObject *self;
1194 PyObject *args;
1196 PyObject *line;
1197 char *str;
1198 PyObject *res;
1199 PyObject *globals, *locals;
1201 line = builtin_raw_input(self, args);
1202 if (line == NULL)
1203 return line;
1204 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1205 return NULL;
1206 while (*str == ' ' || *str == '\t')
1207 str++;
1208 globals = PyEval_GetGlobals();
1209 locals = PyEval_GetLocals();
1210 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1211 if (PyDict_SetItemString(globals, "__builtins__",
1212 PyEval_GetBuiltins()) != 0)
1213 return NULL;
1215 res = PyRun_String(str, Py_eval_input, globals, locals);
1216 Py_DECREF(line);
1217 return res;
1220 static char input_doc[] =
1221 "input([prompt]) -> value\n\
1223 Equivalent to eval(raw_input(prompt)).";
1226 static PyObject *
1227 builtin_intern(self, args)
1228 PyObject *self;
1229 PyObject *args;
1231 PyObject *s;
1232 if (!PyArg_ParseTuple(args, "S", &s))
1233 return NULL;
1234 Py_INCREF(s);
1235 PyString_InternInPlace(&s);
1236 return s;
1239 static char intern_doc[] =
1240 "intern(string) -> string\n\
1242 ``Intern'' the given string. This enters the string in the (global)\n\
1243 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1244 Return the string itself or the previously interned string object with the\n\
1245 same value.";
1248 static PyObject *
1249 builtin_int(self, args)
1250 PyObject *self;
1251 PyObject *args;
1253 PyObject *v;
1255 if (!PyArg_ParseTuple(args, "O:int", &v))
1256 return NULL;
1257 return PyNumber_Int(v);
1260 static char int_doc[] =
1261 "int(x) -> integer\n\
1263 Convert a string or number to an integer, if possible.\n\
1264 A floating point argument will be truncated towards zero.";
1267 static PyObject *
1268 builtin_len(self, args)
1269 PyObject *self;
1270 PyObject *args;
1272 PyObject *v;
1273 long res;
1275 if (!PyArg_ParseTuple(args, "O:len", &v))
1276 return NULL;
1277 res = PyObject_Length(v);
1278 if (res < 0 && PyErr_Occurred())
1279 return NULL;
1280 return PyInt_FromLong(res);
1283 static char len_doc[] =
1284 "len(object) -> integer\n\
1286 Return the number of items of a sequence or mapping.";
1289 static PyObject *
1290 builtin_list(self, args)
1291 PyObject *self;
1292 PyObject *args;
1294 PyObject *v;
1296 if (!PyArg_ParseTuple(args, "O:list", &v))
1297 return NULL;
1298 return PySequence_List(v);
1301 static char list_doc[] =
1302 "list(sequence) -> list\n\
1304 Return a new list whose items are the same as those of the argument sequence.";
1307 static PyObject *
1308 builtin_slice(self, args)
1309 PyObject *self;
1310 PyObject *args;
1312 PyObject *start, *stop, *step;
1314 start = stop = step = NULL;
1316 if (!PyArg_ParseTuple(args, "O|OO:slice", &start, &stop, &step))
1317 return NULL;
1319 /* This swapping of stop and start is to maintain similarity with
1320 range(). */
1321 if (stop == NULL) {
1322 stop = start;
1323 start = NULL;
1325 return PySlice_New(start, stop, step);
1328 static char slice_doc[] =
1329 "slice([start,] stop[, step]) -> slice object\n\
1331 Create a slice object. This is used for slicing by the Numeric extensions.";
1334 static PyObject *
1335 builtin_locals(self, args)
1336 PyObject *self;
1337 PyObject *args;
1339 PyObject *d;
1341 if (!PyArg_ParseTuple(args, ""))
1342 return NULL;
1343 d = PyEval_GetLocals();
1344 Py_INCREF(d);
1345 return d;
1348 static char locals_doc[] =
1349 "locals() -> dictionary\n\
1351 Return the dictionary containing the current scope's local variables.";
1354 static PyObject *
1355 builtin_long(self, args)
1356 PyObject *self;
1357 PyObject *args;
1359 PyObject *v;
1361 if (!PyArg_ParseTuple(args, "O:long", &v))
1362 return NULL;
1363 return PyNumber_Long(v);
1366 static char long_doc[] =
1367 "long(x) -> long integer\n\
1369 Convert a string or number to a long integer, if possible.\n\
1370 A floating point argument will be truncated towards zero.";
1373 static PyObject *
1374 min_max(args, sign)
1375 PyObject *args;
1376 int sign;
1378 int i;
1379 PyObject *v, *w, *x;
1380 PySequenceMethods *sq;
1382 if (PyTuple_Size(args) > 1)
1383 v = args;
1384 else if (!PyArg_ParseTuple(args, "O:min/max", &v))
1385 return NULL;
1386 sq = v->ob_type->tp_as_sequence;
1387 if (sq == NULL || sq->sq_item == NULL) {
1388 PyErr_SetString(PyExc_TypeError,
1389 "min() or max() of non-sequence");
1390 return NULL;
1392 w = NULL;
1393 for (i = 0; ; i++) {
1394 x = (*sq->sq_item)(v, i); /* Implies INCREF */
1395 if (x == NULL) {
1396 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
1397 PyErr_Clear();
1398 break;
1400 Py_XDECREF(w);
1401 return NULL;
1403 if (w == NULL)
1404 w = x;
1405 else {
1406 int c = PyObject_Compare(x, w);
1407 if (c && PyErr_Occurred()) {
1408 Py_DECREF(x);
1409 Py_XDECREF(w);
1410 return NULL;
1412 if (c * sign > 0) {
1413 Py_DECREF(w);
1414 w = x;
1416 else
1417 Py_DECREF(x);
1420 if (w == NULL)
1421 PyErr_SetString(PyExc_ValueError,
1422 "min() or max() of empty sequence");
1423 return w;
1426 static PyObject *
1427 builtin_min(self, v)
1428 PyObject *self;
1429 PyObject *v;
1431 return min_max(v, -1);
1434 static char min_doc[] =
1435 "min(sequence) -> value\n\
1436 min(a, b, c, ...) -> value\n\
1438 With a single sequence argument, return its smallest item.\n\
1439 With two or more arguments, return the smallest argument.";
1442 static PyObject *
1443 builtin_max(self, v)
1444 PyObject *self;
1445 PyObject *v;
1447 return min_max(v, 1);
1450 static char max_doc[] =
1451 "max(sequence) -> value\n\
1452 max(a, b, c, ...) -> value\n\
1454 With a single sequence argument, return its largest item.\n\
1455 With two or more arguments, return the largest argument.";
1458 static PyObject *
1459 builtin_oct(self, args)
1460 PyObject *self;
1461 PyObject *args;
1463 PyObject *v;
1464 PyNumberMethods *nb;
1466 if (!PyArg_ParseTuple(args, "O:oct", &v))
1467 return NULL;
1468 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1469 nb->nb_oct == NULL) {
1470 PyErr_SetString(PyExc_TypeError,
1471 "oct() argument can't be converted to oct");
1472 return NULL;
1474 return (*nb->nb_oct)(v);
1477 static char oct_doc[] =
1478 "oct(number) -> string\n\
1480 Return the octal representation of an integer or long integer.";
1483 static PyObject *
1484 builtin_open(self, args)
1485 PyObject *self;
1486 PyObject *args;
1488 char *name;
1489 char *mode = "r";
1490 int bufsize = -1;
1491 PyObject *f;
1493 if (!PyArg_ParseTuple(args, "s|si:open", &name, &mode, &bufsize))
1494 return NULL;
1495 f = PyFile_FromString(name, mode);
1496 if (f != NULL)
1497 PyFile_SetBufSize(f, bufsize);
1498 return f;
1501 static char open_doc[] =
1502 "open(filename[, mode[, buffering]]) -> file object\n\
1504 Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n\
1505 writing or appending. The file will be created if it doesn't exist\n\
1506 when opened for writing or appending; it will be truncated when\n\
1507 opened for writing. Add a 'b' to the mode for binary files.\n\
1508 Add a '+' to the mode to allow simultaneous reading and writing.\n\
1509 If the buffering argument is given, 0 means unbuffered, 1 means line\n\
1510 buffered, and larger numbers specify the buffer size.";
1513 static PyObject *
1514 builtin_ord(self, args)
1515 PyObject *self;
1516 PyObject *args;
1518 char c;
1520 if (!PyArg_ParseTuple(args, "c:ord", &c))
1521 return NULL;
1522 return PyInt_FromLong((long)(c & 0xff));
1525 static char ord_doc[] =
1526 "ord(c) -> integer\n\
1528 Return the integer ordinal of a one character string.";
1531 static PyObject *
1532 builtin_pow(self, args)
1533 PyObject *self;
1534 PyObject *args;
1536 PyObject *v, *w, *z = Py_None;
1538 if (!PyArg_ParseTuple(args, "OO|O:pow", &v, &w, &z))
1539 return NULL;
1540 return PyNumber_Power(v, w, z);
1543 static char pow_doc[] =
1544 "pow(x, y[, z]) -> number\n\
1546 With two arguments, equivalent to x**y. With three arguments,\n\
1547 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).";
1550 /* Return number of items in range/xrange (lo, hi, step). step > 0
1551 * required. Return a value < 0 if & only if the true value is too
1552 * large to fit in a signed long.
1554 static long
1555 get_len_of_range(lo, hi, step)
1556 long lo;
1557 long hi;
1558 long step; /* must be > 0 */
1560 /* -------------------------------------------------------------
1561 If lo >= hi, the range is empty.
1562 Else if n values are in the range, the last one is
1563 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1564 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1565 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1566 the RHS is non-negative and so truncation is the same as the
1567 floor. Letting M be the largest positive long, the worst case
1568 for the RHS numerator is hi=M, lo=-M-1, and then
1569 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1570 precision to compute the RHS exactly.
1571 ---------------------------------------------------------------*/
1572 long n = 0;
1573 if (lo < hi) {
1574 unsigned long uhi = (unsigned long)hi;
1575 unsigned long ulo = (unsigned long)lo;
1576 unsigned long diff = uhi - ulo - 1;
1577 n = (long)(diff / (unsigned long)step + 1);
1579 return n;
1582 static PyObject *
1583 builtin_range(self, args)
1584 PyObject *self;
1585 PyObject *args;
1587 long ilow = 0, ihigh = 0, istep = 1;
1588 long bign;
1589 int i, n;
1591 PyObject *v;
1593 if (PyTuple_Size(args) <= 1) {
1594 if (!PyArg_ParseTuple(args,
1595 "l;range() requires 1-3 int arguments",
1596 &ihigh))
1597 return NULL;
1599 else {
1600 if (!PyArg_ParseTuple(args,
1601 "ll|l;range() requires 1-3 int arguments",
1602 &ilow, &ihigh, &istep))
1603 return NULL;
1605 if (istep == 0) {
1606 PyErr_SetString(PyExc_ValueError, "zero step for range()");
1607 return NULL;
1609 if (istep > 0)
1610 bign = get_len_of_range(ilow, ihigh, istep);
1611 else
1612 bign = get_len_of_range(ihigh, ilow, -istep);
1613 n = (int)bign;
1614 if (bign < 0 || (long)n != bign) {
1615 PyErr_SetString(PyExc_OverflowError,
1616 "range() has too many items");
1617 return NULL;
1619 v = PyList_New(n);
1620 if (v == NULL)
1621 return NULL;
1622 for (i = 0; i < n; i++) {
1623 PyObject *w = PyInt_FromLong(ilow);
1624 if (w == NULL) {
1625 Py_DECREF(v);
1626 return NULL;
1628 PyList_SET_ITEM(v, i, w);
1629 ilow += istep;
1631 return v;
1634 static char range_doc[] =
1635 "range([start,] stop[, step]) -> list of integers\n\
1637 Return a list containing an arithmetic progression of integers.\n\
1638 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1639 When step is given, it specifies the increment (or decrement).\n\
1640 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1641 These are exactly the valid indices for a list of 4 elements.";
1644 static PyObject *
1645 builtin_xrange(self, args)
1646 PyObject *self;
1647 PyObject *args;
1649 long ilow = 0, ihigh = 0, istep = 1;
1650 long n;
1652 if (PyTuple_Size(args) <= 1) {
1653 if (!PyArg_ParseTuple(args,
1654 "l;xrange() requires 1-3 int arguments",
1655 &ihigh))
1656 return NULL;
1658 else {
1659 if (!PyArg_ParseTuple(args,
1660 "ll|l;xrange() requires 1-3 int arguments",
1661 &ilow, &ihigh, &istep))
1662 return NULL;
1664 if (istep == 0) {
1665 PyErr_SetString(PyExc_ValueError, "zero step for xrange()");
1666 return NULL;
1668 if (istep > 0)
1669 n = get_len_of_range(ilow, ihigh, istep);
1670 else
1671 n = get_len_of_range(ihigh, ilow, -istep);
1672 if (n < 0) {
1673 PyErr_SetString(PyExc_OverflowError,
1674 "xrange() has more than sys.maxint items");
1675 return NULL;
1677 return PyRange_New(ilow, n, istep, 1);
1680 static char xrange_doc[] =
1681 "xrange([start,] stop[, step]) -> xrange object\n\
1683 Like range(), but instead of returning a list, returns an object that\n\
1684 generates the numbers in the range on demand. This is slightly slower\n\
1685 than range() but more memory efficient.";
1688 static PyObject *
1689 builtin_raw_input(self, args)
1690 PyObject *self;
1691 PyObject *args;
1693 PyObject *v = NULL;
1694 PyObject *f;
1696 if (!PyArg_ParseTuple(args, "|O:[raw_]input", &v))
1697 return NULL;
1698 if (PyFile_AsFile(PySys_GetObject("stdin")) == stdin &&
1699 PyFile_AsFile(PySys_GetObject("stdout")) == stdout &&
1700 isatty(fileno(stdin)) && isatty(fileno(stdout))) {
1701 PyObject *po;
1702 char *prompt;
1703 char *s;
1704 PyObject *result;
1705 if (v != NULL) {
1706 po = PyObject_Str(v);
1707 if (po == NULL)
1708 return NULL;
1709 prompt = PyString_AsString(po);
1710 if (prompt == NULL)
1711 return NULL;
1713 else {
1714 po = NULL;
1715 prompt = "";
1717 s = PyOS_Readline(prompt);
1718 Py_XDECREF(po);
1719 if (s == NULL) {
1720 PyErr_SetNone(PyExc_KeyboardInterrupt);
1721 return NULL;
1723 if (*s == '\0') {
1724 PyErr_SetNone(PyExc_EOFError);
1725 result = NULL;
1727 else { /* strip trailing '\n' */
1728 result = PyString_FromStringAndSize(s, strlen(s)-1);
1730 free(s);
1731 return result;
1733 if (v != NULL) {
1734 f = PySys_GetObject("stdout");
1735 if (f == NULL) {
1736 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1737 return NULL;
1739 if (Py_FlushLine() != 0 ||
1740 PyFile_WriteObject(v, f, Py_PRINT_RAW) != 0)
1741 return NULL;
1743 f = PySys_GetObject("stdin");
1744 if (f == NULL) {
1745 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdin");
1746 return NULL;
1748 return PyFile_GetLine(f, -1);
1751 static char raw_input_doc[] =
1752 "raw_input([prompt]) -> string\n\
1754 Read a string from standard input. The trailing newline is stripped.\n\
1755 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1756 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1757 is printed without a trailing newline before reading.";
1760 static PyObject *
1761 builtin_reduce(self, args)
1762 PyObject *self;
1763 PyObject *args;
1765 PyObject *seq, *func, *result = NULL;
1766 PySequenceMethods *sqf;
1767 register int i;
1769 if (!PyArg_ParseTuple(args, "OO|O:reduce", &func, &seq, &result))
1770 return NULL;
1771 if (result != NULL)
1772 Py_INCREF(result);
1774 sqf = seq->ob_type->tp_as_sequence;
1775 if (sqf == NULL || sqf->sq_item == NULL) {
1776 PyErr_SetString(PyExc_TypeError,
1777 "2nd argument to reduce() must be a sequence object");
1778 return NULL;
1781 if ((args = PyTuple_New(2)) == NULL)
1782 goto Fail;
1784 for (i = 0; ; ++i) {
1785 PyObject *op2;
1787 if (args->ob_refcnt > 1) {
1788 Py_DECREF(args);
1789 if ((args = PyTuple_New(2)) == NULL)
1790 goto Fail;
1793 if ((op2 = (*sqf->sq_item)(seq, i)) == NULL) {
1794 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
1795 PyErr_Clear();
1796 break;
1798 goto Fail;
1801 if (result == NULL)
1802 result = op2;
1803 else {
1804 PyTuple_SetItem(args, 0, result);
1805 PyTuple_SetItem(args, 1, op2);
1806 if ((result = PyEval_CallObject(func, args)) == NULL)
1807 goto Fail;
1811 Py_DECREF(args);
1813 if (result == NULL)
1814 PyErr_SetString(PyExc_TypeError,
1815 "reduce of empty sequence with no initial value");
1817 return result;
1819 Fail:
1820 Py_XDECREF(args);
1821 Py_XDECREF(result);
1822 return NULL;
1825 static char reduce_doc[] =
1826 "reduce(function, sequence[, initial]) -> value\n\
1828 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1829 from left to right, so as to reduce the sequence to a single value.\n\
1830 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1831 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1832 of the sequence in the calculation, and serves as a default when the\n\
1833 sequence is empty.";
1836 static PyObject *
1837 builtin_reload(self, args)
1838 PyObject *self;
1839 PyObject *args;
1841 PyObject *v;
1843 if (!PyArg_ParseTuple(args, "O:reload", &v))
1844 return NULL;
1845 return PyImport_ReloadModule(v);
1848 static char reload_doc[] =
1849 "reload(module) -> module\n\
1851 Reload the module. The module must have been successfully imported before.";
1854 static PyObject *
1855 builtin_repr(self, args)
1856 PyObject *self;
1857 PyObject *args;
1859 PyObject *v;
1861 if (!PyArg_ParseTuple(args, "O:repr", &v))
1862 return NULL;
1863 return PyObject_Repr(v);
1866 static char repr_doc[] =
1867 "repr(object) -> string\n\
1869 Return the canonical string representation of the object.\n\
1870 For most object types, eval(repr(object)) == object.";
1873 static PyObject *
1874 builtin_round(self, args)
1875 PyObject *self;
1876 PyObject *args;
1878 double x;
1879 double f;
1880 int ndigits = 0;
1881 int i;
1883 if (!PyArg_ParseTuple(args, "d|i:round", &x, &ndigits))
1884 return NULL;
1885 f = 1.0;
1886 i = abs(ndigits);
1887 while (--i >= 0)
1888 f = f*10.0;
1889 if (ndigits < 0)
1890 x /= f;
1891 else
1892 x *= f;
1893 if (x >= 0.0)
1894 x = floor(x + 0.5);
1895 else
1896 x = ceil(x - 0.5);
1897 if (ndigits < 0)
1898 x *= f;
1899 else
1900 x /= f;
1901 return PyFloat_FromDouble(x);
1904 static char round_doc[] =
1905 "round(number[, ndigits]) -> floating point number\n\
1907 Round a number to a given precision in decimal digits (default 0 digits).\n\
1908 This always returns a floating point number. Precision may be negative.";
1911 static PyObject *
1912 builtin_str(self, args)
1913 PyObject *self;
1914 PyObject *args;
1916 PyObject *v;
1918 if (!PyArg_ParseTuple(args, "O:str", &v))
1919 return NULL;
1920 return PyObject_Str(v);
1923 static char str_doc[] =
1924 "str(object) -> string\n\
1926 Return a nice string representation of the object.\n\
1927 If the argument is a string, the return value is the same object.";
1930 static PyObject *
1931 builtin_tuple(self, args)
1932 PyObject *self;
1933 PyObject *args;
1935 PyObject *v;
1937 if (!PyArg_ParseTuple(args, "O:tuple", &v))
1938 return NULL;
1939 return PySequence_Tuple(v);
1942 static char tuple_doc[] =
1943 "tuple(sequence) -> list\n\
1945 Return a tuple whose items are the same as those of the argument sequence.\n\
1946 If the argument is a tuple, the return value is the same object.";
1949 static PyObject *
1950 builtin_type(self, args)
1951 PyObject *self;
1952 PyObject *args;
1954 PyObject *v;
1956 if (!PyArg_ParseTuple(args, "O:type", &v))
1957 return NULL;
1958 v = (PyObject *)v->ob_type;
1959 Py_INCREF(v);
1960 return v;
1963 static char type_doc[] =
1964 "type(object) -> type object\n\
1966 Return the type of the object.";
1969 static PyObject *
1970 builtin_vars(self, args)
1971 PyObject *self;
1972 PyObject *args;
1974 PyObject *v = NULL;
1975 PyObject *d;
1977 if (!PyArg_ParseTuple(args, "|O:vars", &v))
1978 return NULL;
1979 if (v == NULL) {
1980 d = PyEval_GetLocals();
1981 if (d == NULL) {
1982 if (!PyErr_Occurred())
1983 PyErr_SetString(PyExc_SystemError,
1984 "no locals!?");
1986 else
1987 Py_INCREF(d);
1989 else {
1990 d = PyObject_GetAttrString(v, "__dict__");
1991 if (d == NULL) {
1992 PyErr_SetString(PyExc_TypeError,
1993 "vars() argument must have __dict__ attribute");
1994 return NULL;
1997 return d;
2000 static char vars_doc[] =
2001 "vars([object]) -> dictionary\n\
2003 Without arguments, equivalent to locals().\n\
2004 With an argument, equivalent to object.__dict__.";
2006 static int
2007 abstract_issubclass(derived, cls, err, first)
2008 PyObject *derived;
2009 PyObject *cls;
2010 char *err;
2011 int first;
2013 static PyObject *__bases__ = NULL;
2014 PyObject *bases;
2015 int i, n;
2016 int r = 0;
2018 if (__bases__ == NULL) {
2019 __bases__ = PyString_FromString("__bases__");
2020 if (__bases__ == NULL)
2021 return -1;
2024 if (first) {
2025 bases = PyObject_GetAttr(cls, __bases__);
2026 if (bases == NULL || !PyTuple_Check(bases)) {
2027 Py_XDECREF(bases);
2028 PyErr_SetString(PyExc_TypeError, err);
2029 return -1;
2031 Py_DECREF(bases);
2034 if (derived == cls)
2035 return 1;
2037 bases = PyObject_GetAttr(derived, __bases__);
2038 if (bases == NULL || !PyTuple_Check(bases)) {
2039 Py_XDECREF(bases);
2040 PyErr_SetString(PyExc_TypeError, err);
2041 return -1;
2044 n = PyTuple_GET_SIZE(bases);
2045 for (i = 0; i < n; i++) {
2046 r = abstract_issubclass(PyTuple_GET_ITEM(bases, i),
2047 cls, err, 0);
2048 if (r != 0)
2049 break;
2052 Py_DECREF(bases);
2054 return r;
2057 static PyObject *
2058 builtin_isinstance(self, args)
2059 PyObject *self;
2060 PyObject *args;
2062 PyObject *inst;
2063 PyObject *cls;
2064 PyObject *icls;
2065 static PyObject *__class__ = NULL;
2066 int retval = 0;
2068 if (!PyArg_ParseTuple(args, "OO", &inst, &cls))
2069 return NULL;
2071 if (PyClass_Check(cls)) {
2072 if (PyInstance_Check(inst)) {
2073 PyObject *inclass =
2074 (PyObject*)((PyInstanceObject*)inst)->in_class;
2075 retval = PyClass_IsSubclass(inclass, cls);
2078 else if (PyType_Check(cls)) {
2079 retval = ((PyObject *)(inst->ob_type) == cls);
2081 else if (!PyInstance_Check(inst)) {
2082 if (__class__ == NULL) {
2083 __class__ = PyString_FromString("__class__");
2084 if (__class__ == NULL)
2085 return NULL;
2087 icls = PyObject_GetAttr(inst, __class__);
2088 if (icls != NULL) {
2089 retval = abstract_issubclass(
2090 icls, cls,
2091 "second argument must be a class",
2093 Py_DECREF(icls);
2094 if (retval < 0)
2095 return NULL;
2097 else {
2098 PyErr_SetString(PyExc_TypeError,
2099 "second argument must be a class");
2100 return NULL;
2103 else {
2104 PyErr_SetString(PyExc_TypeError,
2105 "second argument must be a class");
2106 return NULL;
2108 return PyInt_FromLong(retval);
2111 static char isinstance_doc[] =
2112 "isinstance(object, class-or-type) -> Boolean\n\
2114 Return whether an object is an instance of a class or of a subclass thereof.\n\
2115 With a type as second argument, return whether that is the object's type.";
2118 static PyObject *
2119 builtin_issubclass(self, args)
2120 PyObject *self;
2121 PyObject *args;
2123 PyObject *derived;
2124 PyObject *cls;
2125 int retval;
2127 if (!PyArg_ParseTuple(args, "OO", &derived, &cls))
2128 return NULL;
2130 if (!PyClass_Check(derived) || !PyClass_Check(cls)) {
2131 retval = abstract_issubclass(
2132 derived, cls, "arguments must be classes", 1);
2133 if (retval < 0)
2134 return NULL;
2136 else {
2137 /* shortcut */
2138 if (!(retval = (derived == cls)))
2139 retval = PyClass_IsSubclass(derived, cls);
2142 return PyInt_FromLong(retval);
2145 static char issubclass_doc[] =
2146 "issubclass(C, B) -> Boolean\n\
2148 Return whether class C is a subclass (i.e., a derived class) of class B.";
2151 static PyMethodDef builtin_methods[] = {
2152 {"__import__", builtin___import__, 1, import_doc},
2153 {"abs", builtin_abs, 1, abs_doc},
2154 {"apply", builtin_apply, 1, apply_doc},
2155 {"buffer", builtin_buffer, 1, buffer_doc},
2156 {"callable", builtin_callable, 1, callable_doc},
2157 {"chr", builtin_chr, 1, chr_doc},
2158 {"cmp", builtin_cmp, 1, cmp_doc},
2159 {"coerce", builtin_coerce, 1, coerce_doc},
2160 {"compile", builtin_compile, 1, compile_doc},
2161 #ifndef WITHOUT_COMPLEX
2162 {"complex", builtin_complex, 1, complex_doc},
2163 #endif
2164 {"delattr", builtin_delattr, 1, delattr_doc},
2165 {"dir", builtin_dir, 1, dir_doc},
2166 {"divmod", builtin_divmod, 1, divmod_doc},
2167 {"eval", builtin_eval, 1, eval_doc},
2168 {"execfile", builtin_execfile, 1, execfile_doc},
2169 {"filter", builtin_filter, 1, filter_doc},
2170 {"float", builtin_float, 1, float_doc},
2171 {"getattr", builtin_getattr, 1, getattr_doc},
2172 {"globals", builtin_globals, 1, globals_doc},
2173 {"hasattr", builtin_hasattr, 1, hasattr_doc},
2174 {"hash", builtin_hash, 1, hash_doc},
2175 {"hex", builtin_hex, 1, hex_doc},
2176 {"id", builtin_id, 1, id_doc},
2177 {"input", builtin_input, 1, input_doc},
2178 {"intern", builtin_intern, 1, intern_doc},
2179 {"int", builtin_int, 1, int_doc},
2180 {"isinstance", builtin_isinstance, 1, isinstance_doc},
2181 {"issubclass", builtin_issubclass, 1, issubclass_doc},
2182 {"len", builtin_len, 1, len_doc},
2183 {"list", builtin_list, 1, list_doc},
2184 {"locals", builtin_locals, 1, locals_doc},
2185 {"long", builtin_long, 1, long_doc},
2186 {"map", builtin_map, 1, map_doc},
2187 {"max", builtin_max, 1, max_doc},
2188 {"min", builtin_min, 1, min_doc},
2189 {"oct", builtin_oct, 1, oct_doc},
2190 {"open", builtin_open, 1, open_doc},
2191 {"ord", builtin_ord, 1, ord_doc},
2192 {"pow", builtin_pow, 1, pow_doc},
2193 {"range", builtin_range, 1, range_doc},
2194 {"raw_input", builtin_raw_input, 1, raw_input_doc},
2195 {"reduce", builtin_reduce, 1, reduce_doc},
2196 {"reload", builtin_reload, 1, reload_doc},
2197 {"repr", builtin_repr, 1, repr_doc},
2198 {"round", builtin_round, 1, round_doc},
2199 {"setattr", builtin_setattr, 1, setattr_doc},
2200 {"slice", builtin_slice, 1, slice_doc},
2201 {"str", builtin_str, 1, str_doc},
2202 {"tuple", builtin_tuple, 1, tuple_doc},
2203 {"type", builtin_type, 1, type_doc},
2204 {"vars", builtin_vars, 1, vars_doc},
2205 {"xrange", builtin_xrange, 1, xrange_doc},
2206 {NULL, NULL},
2209 /* Predefined exceptions */
2211 PyObject *PyExc_Exception;
2212 PyObject *PyExc_StandardError;
2213 PyObject *PyExc_ArithmeticError;
2214 PyObject *PyExc_LookupError;
2216 PyObject *PyExc_AssertionError;
2217 PyObject *PyExc_AttributeError;
2218 PyObject *PyExc_EOFError;
2219 PyObject *PyExc_FloatingPointError;
2220 PyObject *PyExc_EnvironmentError;
2221 PyObject *PyExc_IOError;
2222 PyObject *PyExc_OSError;
2223 PyObject *PyExc_ImportError;
2224 PyObject *PyExc_IndexError;
2225 PyObject *PyExc_KeyError;
2226 PyObject *PyExc_KeyboardInterrupt;
2227 PyObject *PyExc_MemoryError;
2228 PyObject *PyExc_NameError;
2229 PyObject *PyExc_OverflowError;
2230 PyObject *PyExc_RuntimeError;
2231 PyObject *PyExc_NotImplementedError;
2232 PyObject *PyExc_SyntaxError;
2233 PyObject *PyExc_SystemError;
2234 PyObject *PyExc_SystemExit;
2235 PyObject *PyExc_UnboundLocalError;
2236 PyObject *PyExc_TypeError;
2237 PyObject *PyExc_ValueError;
2238 PyObject *PyExc_ZeroDivisionError;
2240 PyObject *PyExc_MemoryErrorInst;
2242 static struct
2244 char* name;
2245 PyObject** exc;
2246 int leaf_exc;
2248 bltin_exc[] = {
2249 {"Exception", &PyExc_Exception, 0},
2250 {"StandardError", &PyExc_StandardError, 0},
2251 {"ArithmeticError", &PyExc_ArithmeticError, 0},
2252 {"LookupError", &PyExc_LookupError, 0},
2253 {"AssertionError", &PyExc_AssertionError, 1},
2254 {"AttributeError", &PyExc_AttributeError, 1},
2255 {"EOFError", &PyExc_EOFError, 1},
2256 {"FloatingPointError", &PyExc_FloatingPointError, 1},
2257 {"EnvironmentError", &PyExc_EnvironmentError, 0},
2258 {"IOError", &PyExc_IOError, 1},
2259 {"OSError", &PyExc_OSError, 1},
2260 {"ImportError", &PyExc_ImportError, 1},
2261 {"IndexError", &PyExc_IndexError, 1},
2262 {"KeyError", &PyExc_KeyError, 1},
2263 {"KeyboardInterrupt", &PyExc_KeyboardInterrupt, 1},
2264 {"MemoryError", &PyExc_MemoryError, 1},
2265 /* Note: NameError is not a leaf in exceptions.py, but unlike
2266 the other non-leafs NameError is meant to be raised directly
2267 at times -- the leaf_exc member really seems to mean something
2268 like "this is an abstract base class" when false.
2270 {"NameError", &PyExc_NameError, 1},
2271 {"OverflowError", &PyExc_OverflowError, 1},
2272 {"RuntimeError", &PyExc_RuntimeError, 1},
2273 {"NotImplementedError",&PyExc_NotImplementedError,1},
2274 {"SyntaxError", &PyExc_SyntaxError, 1},
2275 {"SystemError", &PyExc_SystemError, 1},
2276 {"SystemExit", &PyExc_SystemExit, 1},
2277 {"UnboundLocalError", &PyExc_UnboundLocalError, 1},
2278 {"TypeError", &PyExc_TypeError, 1},
2279 {"ValueError", &PyExc_ValueError, 1},
2280 {"ZeroDivisionError", &PyExc_ZeroDivisionError, 1},
2281 {NULL, NULL}
2285 /* import exceptions module to extract class exceptions. on success,
2286 * return 1. on failure return 0 which signals _PyBuiltin_Init_2 to fall
2287 * back to using old-style string based exceptions.
2289 static int
2290 init_class_exc(dict)
2291 PyObject *dict;
2293 int i;
2294 PyObject *m = PyImport_ImportModule("exceptions");
2295 PyObject *args = NULL;
2296 PyObject *d = NULL;
2298 /* make sure we got the module and its dictionary */
2299 if (m == NULL ||
2300 (d = PyModule_GetDict(m)) == NULL)
2302 PySys_WriteStderr("'import exceptions' failed; ");
2303 if (Py_VerboseFlag) {
2304 PySys_WriteStderr("traceback:\n");
2305 PyErr_Print();
2307 else {
2308 PySys_WriteStderr("use -v for traceback\n");
2310 goto finally;
2312 for (i = 0; bltin_exc[i].name; i++) {
2313 /* dig the exception out of the module */
2314 PyObject *exc = PyDict_GetItemString(d, bltin_exc[i].name);
2315 if (!exc) {
2316 PySys_WriteStderr(
2317 "Built-in exception class not found: %s. Library mismatch?\n",
2318 bltin_exc[i].name);
2319 goto finally;
2321 /* free the old-style exception string object */
2322 Py_XDECREF(*bltin_exc[i].exc);
2324 /* squirrel away a pointer to the exception */
2325 Py_INCREF(exc);
2326 *bltin_exc[i].exc = exc;
2328 /* and insert the name in the __builtin__ module */
2329 if (PyDict_SetItemString(dict, bltin_exc[i].name, exc)) {
2330 PySys_WriteStderr(
2331 "Cannot insert exception into __builtin__: %s\n",
2332 bltin_exc[i].name);
2333 goto finally;
2337 /* we need one pre-allocated instance */
2338 args = Py_BuildValue("()");
2339 if (!args ||
2340 !(PyExc_MemoryErrorInst =
2341 PyEval_CallObject(PyExc_MemoryError, args)))
2343 PySys_WriteStderr("Cannot pre-allocate MemoryError instance\n");
2344 goto finally;
2346 Py_DECREF(args);
2348 /* we're done with the exceptions module */
2349 Py_DECREF(m);
2351 if (PyErr_Occurred()) {
2352 PySys_WriteStderr("Cannot initialize standard class exceptions; ");
2353 if (Py_VerboseFlag) {
2354 PySys_WriteStderr("traceback:\n");
2355 PyErr_Print();
2357 else
2358 PySys_WriteStderr("use -v for traceback\n");
2359 goto finally;
2361 return 1;
2362 finally:
2363 Py_XDECREF(m);
2364 Py_XDECREF(args);
2365 PyErr_Clear();
2366 return 0;
2370 static void
2371 fini_instances()
2373 Py_XDECREF(PyExc_MemoryErrorInst);
2374 PyExc_MemoryErrorInst = NULL;
2378 static PyObject *
2379 newstdexception(dict, name)
2380 PyObject *dict;
2381 char *name;
2383 PyObject *v = PyString_FromString(name);
2384 if (v == NULL || PyDict_SetItemString(dict, name, v) != 0)
2385 Py_FatalError("Cannot create string-based exceptions");
2386 return v;
2389 static void
2390 initerrors(dict)
2391 PyObject *dict;
2393 int i, j;
2394 int exccnt = 0;
2395 for (i = 0; bltin_exc[i].name; i++, exccnt++) {
2396 Py_XDECREF(*bltin_exc[i].exc);
2397 if (bltin_exc[i].leaf_exc)
2398 *bltin_exc[i].exc =
2399 newstdexception(dict, bltin_exc[i].name);
2402 /* This is kind of bogus because we special case the some of the
2403 * new exceptions to be nearly forward compatible. But this means
2404 * we hard code knowledge about exceptions.py into C here. I don't
2405 * have a better solution, though.
2407 PyExc_LookupError = PyTuple_New(2);
2408 Py_INCREF(PyExc_IndexError);
2409 PyTuple_SET_ITEM(PyExc_LookupError, 0, PyExc_IndexError);
2410 Py_INCREF(PyExc_KeyError);
2411 PyTuple_SET_ITEM(PyExc_LookupError, 1, PyExc_KeyError);
2412 PyDict_SetItemString(dict, "LookupError", PyExc_LookupError);
2414 PyExc_ArithmeticError = PyTuple_New(3);
2415 Py_INCREF(PyExc_OverflowError);
2416 PyTuple_SET_ITEM(PyExc_ArithmeticError, 0, PyExc_OverflowError);
2417 Py_INCREF(PyExc_ZeroDivisionError);
2418 PyTuple_SET_ITEM(PyExc_ArithmeticError, 1, PyExc_ZeroDivisionError);
2419 Py_INCREF(PyExc_FloatingPointError);
2420 PyTuple_SET_ITEM(PyExc_ArithmeticError, 2, PyExc_FloatingPointError);
2421 PyDict_SetItemString(dict, "ArithmeticError", PyExc_ArithmeticError);
2423 PyExc_EnvironmentError = PyTuple_New(2);
2424 Py_INCREF(PyExc_IOError);
2425 PyTuple_SET_ITEM(PyExc_EnvironmentError, 0, PyExc_IOError);
2426 Py_INCREF(PyExc_OSError);
2427 PyTuple_SET_ITEM(PyExc_EnvironmentError, 1, PyExc_OSError);
2428 PyDict_SetItemString(dict, "EnvironmentError", PyExc_EnvironmentError);
2430 /* Make UnboundLocalError an alias for NameError */
2431 Py_INCREF(PyExc_NameError);
2432 Py_DECREF(PyExc_UnboundLocalError);
2433 PyExc_UnboundLocalError = PyExc_NameError;
2434 if (PyDict_SetItemString(dict, "UnboundLocalError",
2435 PyExc_NameError) != 0)
2436 Py_FatalError("Cannot create string-based exceptions");
2438 /* missing from the StandardError tuple: Exception, StandardError,
2439 * and SystemExit
2441 PyExc_StandardError = PyTuple_New(exccnt-3);
2442 for (i = 2, j = 0; bltin_exc[i].name; i++) {
2443 PyObject *exc = *bltin_exc[i].exc;
2444 /* SystemExit is not an error, but it is an exception */
2445 if (exc != PyExc_SystemExit) {
2446 Py_INCREF(exc);
2447 PyTuple_SET_ITEM(PyExc_StandardError, j++, exc);
2450 PyDict_SetItemString(dict, "StandardError", PyExc_StandardError);
2452 /* Exception is a 2-tuple */
2453 PyExc_Exception = PyTuple_New(2);
2454 Py_INCREF(PyExc_SystemExit);
2455 PyTuple_SET_ITEM(PyExc_Exception, 0, PyExc_SystemExit);
2456 Py_INCREF(PyExc_StandardError);
2457 PyTuple_SET_ITEM(PyExc_Exception, 1, PyExc_StandardError);
2458 PyDict_SetItemString(dict, "Exception", PyExc_Exception);
2460 if (PyErr_Occurred())
2461 Py_FatalError("Could not initialize built-in string exceptions");
2465 static void
2466 finierrors()
2468 int i;
2469 for (i = 0; bltin_exc[i].name; i++) {
2470 PyObject *exc = *bltin_exc[i].exc;
2471 Py_XDECREF(exc);
2472 *bltin_exc[i].exc = NULL;
2476 static char builtin_doc[] =
2477 "Built-in functions, exceptions, and other objects.\n\
2479 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.";
2481 PyObject *
2482 _PyBuiltin_Init_1()
2484 PyObject *mod, *dict;
2485 mod = Py_InitModule4("__builtin__", builtin_methods,
2486 builtin_doc, (PyObject *)NULL,
2487 PYTHON_API_VERSION);
2488 if (mod == NULL)
2489 return NULL;
2490 dict = PyModule_GetDict(mod);
2491 initerrors(dict);
2492 if (PyDict_SetItemString(dict, "None", Py_None) < 0)
2493 return NULL;
2494 if (PyDict_SetItemString(dict, "Ellipsis", Py_Ellipsis) < 0)
2495 return NULL;
2496 if (PyDict_SetItemString(dict, "__debug__",
2497 PyInt_FromLong(Py_OptimizeFlag == 0)) < 0)
2498 return NULL;
2500 return mod;
2503 void
2504 _PyBuiltin_Init_2(dict)
2505 PyObject *dict;
2507 /* if Python was started with -X, initialize the class exceptions */
2508 if (Py_UseClassExceptionsFlag) {
2509 if (!init_class_exc(dict)) {
2510 /* class based exceptions could not be
2511 * initialized. Fall back to using string based
2512 * exceptions.
2514 PySys_WriteStderr(
2515 "Warning! Falling back to string-based exceptions\n");
2516 initerrors(dict);
2522 void
2523 _PyBuiltin_Fini_1()
2525 fini_instances();
2529 void
2530 _PyBuiltin_Fini_2()
2532 finierrors();
2536 /* Helper for filter(): filter a tuple through a function */
2538 static PyObject *
2539 filtertuple(func, tuple)
2540 PyObject *func;
2541 PyObject *tuple;
2543 PyObject *result;
2544 register int i, j;
2545 int len = PyTuple_Size(tuple);
2547 if (len == 0) {
2548 Py_INCREF(tuple);
2549 return tuple;
2552 if ((result = PyTuple_New(len)) == NULL)
2553 return NULL;
2555 for (i = j = 0; i < len; ++i) {
2556 PyObject *item, *good;
2557 int ok;
2559 if ((item = PyTuple_GetItem(tuple, i)) == NULL)
2560 goto Fail_1;
2561 if (func == Py_None) {
2562 Py_INCREF(item);
2563 good = item;
2565 else {
2566 PyObject *arg = Py_BuildValue("(O)", item);
2567 if (arg == NULL)
2568 goto Fail_1;
2569 good = PyEval_CallObject(func, arg);
2570 Py_DECREF(arg);
2571 if (good == NULL)
2572 goto Fail_1;
2574 ok = PyObject_IsTrue(good);
2575 Py_DECREF(good);
2576 if (ok) {
2577 Py_INCREF(item);
2578 if (PyTuple_SetItem(result, j++, item) < 0)
2579 goto Fail_1;
2583 if (_PyTuple_Resize(&result, j, 0) < 0)
2584 return NULL;
2586 return result;
2588 Fail_1:
2589 Py_DECREF(result);
2590 return NULL;
2594 /* Helper for filter(): filter a string through a function */
2596 static PyObject *
2597 filterstring(func, strobj)
2598 PyObject *func;
2599 PyObject *strobj;
2601 PyObject *result;
2602 register int i, j;
2603 int len = PyString_Size(strobj);
2605 if (func == Py_None) {
2606 /* No character is ever false -- share input string */
2607 Py_INCREF(strobj);
2608 return strobj;
2610 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2611 return NULL;
2613 for (i = j = 0; i < len; ++i) {
2614 PyObject *item, *arg, *good;
2615 int ok;
2617 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2618 if (item == NULL)
2619 goto Fail_1;
2620 arg = Py_BuildValue("(O)", item);
2621 Py_DECREF(item);
2622 if (arg == NULL)
2623 goto Fail_1;
2624 good = PyEval_CallObject(func, arg);
2625 Py_DECREF(arg);
2626 if (good == NULL)
2627 goto Fail_1;
2628 ok = PyObject_IsTrue(good);
2629 Py_DECREF(good);
2630 if (ok)
2631 PyString_AS_STRING((PyStringObject *)result)[j++] =
2632 PyString_AS_STRING((PyStringObject *)item)[0];
2635 if (j < len && _PyString_Resize(&result, j) < 0)
2636 return NULL;
2638 return result;
2640 Fail_1:
2641 Py_DECREF(result);
2642 return NULL;