This commit was manufactured by cvs2svn to create tag 'r16a1'.
[python/dscho.git] / Python / bltinmodule.c
blob90af88854b9499ffc5df4c5a0ceed445abd412a2
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(object, args[, kwargs]) -> value\n\
135 Call a callable object with positional arguments taken from the tuple args,\n\
136 and keyword arguments taken from the optional dictionary kwargs.\n\
137 Note that classes are callable, as are instances with a __call__() method.";
140 static PyObject *
141 builtin_buffer(self, args)
142 PyObject *self;
143 PyObject *args;
145 PyObject *ob;
146 int offset = 0;
147 int size = Py_END_OF_BUFFER;
149 if ( !PyArg_ParseTuple(args, "O|ii:buffer", &ob, &offset, &size) )
150 return NULL;
151 return PyBuffer_FromObject(ob, offset, size);
154 static char buffer_doc[] =
155 "buffer(object [, offset[, size]]) -> object\n\
157 Creates a new buffer object which references the given object.\n\
158 The buffer will reference a slice of the target object from the\n\
159 start of the object (or at the specified offset). The slice will\n\
160 extend to the end of the target object (or with the specified size).";
163 static PyObject *
164 builtin_unicode(self, args)
165 PyObject *self;
166 PyObject *args;
168 char *s;
169 int len;
170 char *encoding = NULL;
171 char *errors = NULL;
173 if ( !PyArg_ParseTuple(args, "s#|ss:unicode", &s, &len,
174 &encoding, &errors) )
175 return NULL;
176 return PyUnicode_Decode(s, len, encoding, errors);
179 static char unicode_doc[] =
180 "unicode(string [, encoding[, errors]]) -> object\n\
182 Creates a new unicode object from the given encoded string.\n\
183 encoding defaults to 'utf-8' and errors, defining the error handling,\n\
184 to 'strict'.";
187 static PyObject *
188 builtin_callable(self, args)
189 PyObject *self;
190 PyObject *args;
192 PyObject *v;
194 if (!PyArg_ParseTuple(args, "O:callable", &v))
195 return NULL;
196 return PyInt_FromLong((long)PyCallable_Check(v));
199 static char callable_doc[] =
200 "callable(object) -> Boolean\n\
202 Return whether the object is callable (i.e., some kind of function).\n\
203 Note that classes are callable, as are instances with a __call__() method.";
206 static PyObject *
207 builtin_filter(self, args)
208 PyObject *self;
209 PyObject *args;
211 PyObject *func, *seq, *result;
212 PySequenceMethods *sqf;
213 int len;
214 register int i, j;
216 if (!PyArg_ParseTuple(args, "OO:filter", &func, &seq))
217 return NULL;
219 if (PyString_Check(seq)) {
220 PyObject *r = filterstring(func, seq);
221 return r;
224 if (PyTuple_Check(seq)) {
225 PyObject *r = filtertuple(func, seq);
226 return r;
229 sqf = seq->ob_type->tp_as_sequence;
230 if (sqf == NULL || sqf->sq_length == NULL || sqf->sq_item == NULL) {
231 PyErr_SetString(PyExc_TypeError,
232 "argument 2 to filter() must be a sequence type");
233 goto Fail_2;
236 if ((len = (*sqf->sq_length)(seq)) < 0)
237 goto Fail_2;
239 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
240 Py_INCREF(seq);
241 result = seq;
243 else {
244 if ((result = PyList_New(len)) == NULL)
245 goto Fail_2;
248 for (i = j = 0; ; ++i) {
249 PyObject *item, *good;
250 int ok;
252 if ((item = (*sqf->sq_item)(seq, i)) == NULL) {
253 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
254 PyErr_Clear();
255 break;
257 goto Fail_1;
260 if (func == Py_None) {
261 good = item;
262 Py_INCREF(good);
264 else {
265 PyObject *arg = Py_BuildValue("(O)", item);
266 if (arg == NULL)
267 goto Fail_1;
268 good = PyEval_CallObject(func, arg);
269 Py_DECREF(arg);
270 if (good == NULL) {
271 Py_DECREF(item);
272 goto Fail_1;
275 ok = PyObject_IsTrue(good);
276 Py_DECREF(good);
277 if (ok) {
278 if (j < len) {
279 if (PyList_SetItem(result, j++, item) < 0)
280 goto Fail_1;
282 else {
283 int status = PyList_Append(result, item);
284 j++;
285 Py_DECREF(item);
286 if (status < 0)
287 goto Fail_1;
289 } else {
290 Py_DECREF(item);
295 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
296 goto Fail_1;
298 return result;
300 Fail_1:
301 Py_DECREF(result);
302 Fail_2:
303 return NULL;
306 static char filter_doc[] =
307 "filter(function, sequence) -> list\n\
309 Return a list containing those items of sequence for which function(item)\n\
310 is true. If function is None, return a list of items that are true.";
313 static PyObject *
314 builtin_chr(self, args)
315 PyObject *self;
316 PyObject *args;
318 long x;
319 char s[1];
321 if (!PyArg_ParseTuple(args, "l:chr", &x))
322 return NULL;
323 if (x < 0 || x >= 256) {
324 PyErr_SetString(PyExc_ValueError,
325 "chr() arg not in range(256)");
326 return NULL;
328 s[0] = (char)x;
329 return PyString_FromStringAndSize(s, 1);
332 static char chr_doc[] =
333 "chr(i) -> character\n\
335 Return a string of one character with ordinal i; 0 <= i < 256.";
338 static PyObject *
339 builtin_unichr(self, args)
340 PyObject *self;
341 PyObject *args;
343 long x;
344 Py_UNICODE s[1];
346 if (!PyArg_ParseTuple(args, "l:unichr", &x))
347 return NULL;
348 if (x < 0 || x >= 65536) {
349 PyErr_SetString(PyExc_ValueError,
350 "unichr() arg not in range(65536)");
351 return NULL;
353 s[0] = (Py_UNICODE)x;
354 return PyUnicode_FromUnicode(s, 1);
357 static char unichr_doc[] =
358 "unichr(i) -> unicode character\n\
360 Return a unicode string of one character with ordinal i; 0 <= i < 65536.";
363 static PyObject *
364 builtin_cmp(self, args)
365 PyObject *self;
366 PyObject *args;
368 PyObject *a, *b;
369 int c;
371 if (!PyArg_ParseTuple(args, "OO:cmp", &a, &b))
372 return NULL;
373 if (PyObject_Cmp(a, b, &c) < 0)
374 return NULL;
375 return PyInt_FromLong((long)c);
378 static char cmp_doc[] =
379 "cmp(x, y) -> integer\n\
381 Return negative if x<y, zero if x==y, positive if x>y.";
384 static PyObject *
385 builtin_coerce(self, args)
386 PyObject *self;
387 PyObject *args;
389 PyObject *v, *w;
390 PyObject *res;
392 if (!PyArg_ParseTuple(args, "OO:coerce", &v, &w))
393 return NULL;
394 if (PyNumber_Coerce(&v, &w) < 0)
395 return NULL;
396 res = Py_BuildValue("(OO)", v, w);
397 Py_DECREF(v);
398 Py_DECREF(w);
399 return res;
402 static char coerce_doc[] =
403 "coerce(x, y) -> None or (x1, y1)\n\
405 When x and y can be coerced to values of the same type, return a tuple\n\
406 containing the coerced values. When they can't be coerced, return None.";
409 static PyObject *
410 builtin_compile(self, args)
411 PyObject *self;
412 PyObject *args;
414 char *str;
415 char *filename;
416 char *startstr;
417 int start;
419 if (!PyArg_ParseTuple(args, "sss:compile", &str, &filename, &startstr))
420 return NULL;
421 if (strcmp(startstr, "exec") == 0)
422 start = Py_file_input;
423 else if (strcmp(startstr, "eval") == 0)
424 start = Py_eval_input;
425 else if (strcmp(startstr, "single") == 0)
426 start = Py_single_input;
427 else {
428 PyErr_SetString(PyExc_ValueError,
429 "compile() mode must be 'exec' or 'eval' or 'single'");
430 return NULL;
432 return Py_CompileString(str, filename, start);
435 static char compile_doc[] =
436 "compile(source, filename, mode) -> code object\n\
438 Compile the source string (a Python module, statement or expression)\n\
439 into a code object that can be executed by the exec statement or eval().\n\
440 The filename will be used for run-time error messages.\n\
441 The mode must be 'exec' to compile a module, 'single' to compile a\n\
442 single (interactive) statement, or 'eval' to compile an expression.";
445 #ifndef WITHOUT_COMPLEX
447 static PyObject *
448 complex_from_string(v)
449 PyObject *v;
451 extern double strtod Py_PROTO((const char *, char **));
452 char *s, *start, *end;
453 double x=0.0, y=0.0, z;
454 int got_re=0, got_im=0, done=0;
455 int digit_or_dot;
456 int sw_error=0;
457 int sign;
458 char buffer[256]; /* For errors */
460 start = s = PyString_AS_STRING(v);
462 /* position on first nonblank */
463 while (*s && isspace(Py_CHARMASK(*s)))
464 s++;
465 if (s[0] == '\0') {
466 PyErr_SetString(PyExc_ValueError,
467 "empty string for complex()");
468 return NULL;
471 z = -1.0;
472 sign = 1;
473 do {
475 switch (*s) {
477 case '\0':
478 if (s-start != PyString_GET_SIZE(v)) {
479 PyErr_SetString(
480 PyExc_ValueError,
481 "null byte in argument for complex()");
482 return NULL;
484 if(!done) sw_error=1;
485 break;
487 case '-':
488 sign = -1;
489 /* Fallthrough */
490 case '+':
491 if (done) sw_error=1;
492 s++;
493 if ( *s=='\0'||*s=='+'||*s=='-' ||
494 isspace(Py_CHARMASK(*s)) ) sw_error=1;
495 break;
497 case 'J':
498 case 'j':
499 if (got_im || done) {
500 sw_error = 1;
501 break;
503 if (z<0.0) {
504 y=sign;
506 else{
507 y=sign*z;
509 got_im=1;
510 s++;
511 if (*s!='+' && *s!='-' )
512 done=1;
513 break;
515 default:
516 if (isspace(Py_CHARMASK(*s))) {
517 while (*s && isspace(Py_CHARMASK(*s)))
518 s++;
519 if (s[0] != '\0')
520 sw_error=1;
521 else
522 done = 1;
523 break;
525 digit_or_dot =
526 (*s=='.' || isdigit(Py_CHARMASK(*s)));
527 if (done||!digit_or_dot) {
528 sw_error=1;
529 break;
531 errno = 0;
532 PyFPE_START_PROTECT("strtod", return 0)
533 z = strtod(s, &end) ;
534 PyFPE_END_PROTECT(z)
535 if (errno != 0) {
536 sprintf(buffer,
537 "float() out of range: %.150s", s);
538 PyErr_SetString(
539 PyExc_ValueError,
540 buffer);
541 return NULL;
543 s=end;
544 if (*s=='J' || *s=='j') {
546 break;
548 if (got_re) {
549 sw_error=1;
550 break;
553 /* accept a real part */
554 x=sign*z;
555 got_re=1;
556 if (got_im) done=1;
557 z = -1.0;
558 sign = 1;
559 break;
561 } /* end of switch */
563 } while (*s!='\0' && !sw_error);
565 if (sw_error) {
566 PyErr_SetString(PyExc_ValueError,
567 "malformed string for complex()");
568 return NULL;
571 return PyComplex_FromDoubles(x,y);
574 static PyObject *
575 builtin_complex(self, args)
576 PyObject *self;
577 PyObject *args;
579 PyObject *r, *i, *tmp;
580 PyNumberMethods *nbr, *nbi = NULL;
581 Py_complex cr, ci;
582 int own_r = 0;
584 i = NULL;
585 if (!PyArg_ParseTuple(args, "O|O:complex", &r, &i))
586 return NULL;
587 if (PyString_Check(r))
588 return complex_from_string(r);
589 if ((nbr = r->ob_type->tp_as_number) == NULL ||
590 nbr->nb_float == NULL ||
591 (i != NULL &&
592 ((nbi = i->ob_type->tp_as_number) == NULL ||
593 nbi->nb_float == NULL))) {
594 PyErr_SetString(PyExc_TypeError,
595 "complex() argument can't be converted to complex");
596 return NULL;
598 /* XXX Hack to support classes with __complex__ method */
599 if (PyInstance_Check(r)) {
600 static PyObject *complexstr;
601 PyObject *f;
602 if (complexstr == NULL) {
603 complexstr = PyString_InternFromString("__complex__");
604 if (complexstr == NULL)
605 return NULL;
607 f = PyObject_GetAttr(r, complexstr);
608 if (f == NULL)
609 PyErr_Clear();
610 else {
611 PyObject *args = Py_BuildValue("()");
612 if (args == NULL)
613 return NULL;
614 r = PyEval_CallObject(f, args);
615 Py_DECREF(args);
616 Py_DECREF(f);
617 if (r == NULL)
618 return NULL;
619 own_r = 1;
622 if (PyComplex_Check(r)) {
623 cr = ((PyComplexObject*)r)->cval;
624 if (own_r) {
625 Py_DECREF(r);
628 else {
629 tmp = (*nbr->nb_float)(r);
630 if (own_r) {
631 Py_DECREF(r);
633 if (tmp == NULL)
634 return NULL;
635 cr.real = PyFloat_AsDouble(tmp);
636 Py_DECREF(tmp);
637 cr.imag = 0.0;
639 if (i == NULL) {
640 ci.real = 0.0;
641 ci.imag = 0.0;
643 else if (PyComplex_Check(i))
644 ci = ((PyComplexObject*)i)->cval;
645 else {
646 tmp = (*nbi->nb_float)(i);
647 if (tmp == NULL)
648 return NULL;
649 ci.real = PyFloat_AsDouble(tmp);
650 Py_DECREF(tmp);
651 ci.imag = 0.;
653 cr.real -= ci.imag;
654 cr.imag += ci.real;
655 return PyComplex_FromCComplex(cr);
658 static char complex_doc[] =
659 "complex(real[, imag]) -> complex number\n\
661 Create a complex number from a real part and an optional imaginary part.\n\
662 This is equivalent to (real + imag*1j) where imag defaults to 0.";
665 #endif
667 static PyObject *
668 builtin_dir(self, args)
669 PyObject *self;
670 PyObject *args;
672 static char *attrlist[] = {"__members__", "__methods__", NULL};
673 PyObject *v = NULL, *l = NULL, *m = NULL;
674 PyObject *d, *x;
675 int i;
676 char **s;
678 if (!PyArg_ParseTuple(args, "|O:dir", &v))
679 return NULL;
680 if (v == NULL) {
681 x = PyEval_GetLocals();
682 if (x == NULL)
683 goto error;
684 l = PyMapping_Keys(x);
685 if (l == NULL)
686 goto error;
688 else {
689 d = PyObject_GetAttrString(v, "__dict__");
690 if (d == NULL)
691 PyErr_Clear();
692 else {
693 l = PyMapping_Keys(d);
694 if (l == NULL)
695 PyErr_Clear();
696 Py_DECREF(d);
698 if (l == NULL) {
699 l = PyList_New(0);
700 if (l == NULL)
701 goto error;
703 for (s = attrlist; *s != NULL; s++) {
704 m = PyObject_GetAttrString(v, *s);
705 if (m == NULL) {
706 PyErr_Clear();
707 continue;
709 for (i = 0; ; i++) {
710 x = PySequence_GetItem(m, i);
711 if (x == NULL) {
712 PyErr_Clear();
713 break;
715 if (PyList_Append(l, x) != 0) {
716 Py_DECREF(x);
717 Py_DECREF(m);
718 goto error;
720 Py_DECREF(x);
722 Py_DECREF(m);
725 if (PyList_Sort(l) != 0)
726 goto error;
727 return l;
728 error:
729 Py_XDECREF(l);
730 return NULL;
733 static char dir_doc[] =
734 "dir([object]) -> list of strings\n\
736 Return an alphabetized list of names comprising (some of) the attributes\n\
737 of the given object. Without an argument, the names in the current scope\n\
738 are listed. With an instance argument, only the instance attributes are\n\
739 returned. With a class argument, attributes of the base class are not\n\
740 returned. For other types or arguments, this may list members or methods.";
743 static PyObject *
744 builtin_divmod(self, args)
745 PyObject *self;
746 PyObject *args;
748 PyObject *v, *w;
750 if (!PyArg_ParseTuple(args, "OO:divmod", &v, &w))
751 return NULL;
752 return PyNumber_Divmod(v, w);
755 static char divmod_doc[] =
756 "divmod(x, y) -> (div, mod)\n\
758 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.";
761 static PyObject *
762 builtin_eval(self, args)
763 PyObject *self;
764 PyObject *args;
766 PyObject *cmd;
767 PyObject *globals = Py_None, *locals = Py_None;
768 char *str;
770 if (!PyArg_ParseTuple(args, "O|O!O!:eval",
771 &cmd,
772 &PyDict_Type, &globals,
773 &PyDict_Type, &locals))
774 return NULL;
775 if (globals == Py_None) {
776 globals = PyEval_GetGlobals();
777 if (locals == Py_None)
778 locals = PyEval_GetLocals();
780 else if (locals == Py_None)
781 locals = globals;
782 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
783 if (PyDict_SetItemString(globals, "__builtins__",
784 PyEval_GetBuiltins()) != 0)
785 return NULL;
787 if (PyCode_Check(cmd))
788 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
789 if (!PyString_Check(cmd)) {
790 PyErr_SetString(PyExc_TypeError,
791 "eval() argument 1 must be string or code object");
792 return NULL;
794 str = PyString_AsString(cmd);
795 if ((int)strlen(str) != PyString_Size(cmd)) {
796 PyErr_SetString(PyExc_ValueError,
797 "embedded '\\0' in string arg");
798 return NULL;
800 while (*str == ' ' || *str == '\t')
801 str++;
802 return PyRun_String(str, Py_eval_input, globals, locals);
805 static char eval_doc[] =
806 "eval(source[, globals[, locals]]) -> value\n\
808 Evaluate the source in the context of globals and locals.\n\
809 The source may be a string representing a Python expression\n\
810 or a code object as returned by compile().\n\
811 The globals and locals are dictionaries, defaulting to the current\n\
812 globals and locals. If only globals is given, locals defaults to it.";
815 static PyObject *
816 builtin_execfile(self, args)
817 PyObject *self;
818 PyObject *args;
820 char *filename;
821 PyObject *globals = Py_None, *locals = Py_None;
822 PyObject *res;
823 FILE* fp;
825 if (!PyArg_ParseTuple(args, "s|O!O!:execfile",
826 &filename,
827 &PyDict_Type, &globals,
828 &PyDict_Type, &locals))
829 return NULL;
830 if (globals == Py_None) {
831 globals = PyEval_GetGlobals();
832 if (locals == Py_None)
833 locals = PyEval_GetLocals();
835 else if (locals == Py_None)
836 locals = globals;
837 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
838 if (PyDict_SetItemString(globals, "__builtins__",
839 PyEval_GetBuiltins()) != 0)
840 return NULL;
842 Py_BEGIN_ALLOW_THREADS
843 fp = fopen(filename, "r");
844 Py_END_ALLOW_THREADS
845 if (fp == NULL) {
846 PyErr_SetFromErrno(PyExc_IOError);
847 return NULL;
849 res = PyRun_File(fp, filename, Py_file_input, globals, locals);
850 Py_BEGIN_ALLOW_THREADS
851 fclose(fp);
852 Py_END_ALLOW_THREADS
853 return res;
856 static char execfile_doc[] =
857 "execfile(filename[, globals[, locals]])\n\
859 Read and execute a Python script from a file.\n\
860 The globals and locals are dictionaries, defaulting to the current\n\
861 globals and locals. If only globals is given, locals defaults to it.";
864 static PyObject *
865 builtin_getattr(self, args)
866 PyObject *self;
867 PyObject *args;
869 PyObject *v, *result, *dflt = NULL;
870 PyObject *name;
872 if (!PyArg_ParseTuple(args, "OS|O:getattr", &v, &name, &dflt))
873 return NULL;
874 result = PyObject_GetAttr(v, name);
875 if (result == NULL && dflt != NULL) {
876 PyErr_Clear();
877 Py_INCREF(dflt);
878 result = dflt;
880 return result;
883 static char getattr_doc[] =
884 "getattr(object, name[, default]) -> value\n\
886 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
887 When a default argument is given, it is returned when the attribute doesn't\n\
888 exist; without it, an exception is raised in that case.";
891 static PyObject *
892 builtin_globals(self, args)
893 PyObject *self;
894 PyObject *args;
896 PyObject *d;
898 if (!PyArg_ParseTuple(args, ":globals"))
899 return NULL;
900 d = PyEval_GetGlobals();
901 Py_INCREF(d);
902 return d;
905 static char globals_doc[] =
906 "globals() -> dictionary\n\
908 Return the dictionary containing the current scope's global variables.";
911 static PyObject *
912 builtin_hasattr(self, args)
913 PyObject *self;
914 PyObject *args;
916 PyObject *v;
917 PyObject *name;
919 if (!PyArg_ParseTuple(args, "OS:hasattr", &v, &name))
920 return NULL;
921 v = PyObject_GetAttr(v, name);
922 if (v == NULL) {
923 PyErr_Clear();
924 Py_INCREF(Py_False);
925 return Py_False;
927 Py_DECREF(v);
928 Py_INCREF(Py_True);
929 return Py_True;
932 static char hasattr_doc[] =
933 "hasattr(object, name) -> Boolean\n\
935 Return whether the object has an attribute with the given name.\n\
936 (This is done by calling getattr(object, name) and catching exceptions.)";
939 static PyObject *
940 builtin_id(self, args)
941 PyObject *self;
942 PyObject *args;
944 PyObject *v;
946 if (!PyArg_ParseTuple(args, "O:id", &v))
947 return NULL;
948 return PyInt_FromLong((long)v);
951 static char id_doc[] =
952 "id(object) -> integer\n\
954 Return the identity of an object. This is guaranteed to be unique among\n\
955 simultaneously existing objects. (Hint: it's the object's memory address.)";
958 static PyObject *
959 builtin_map(self, args)
960 PyObject *self;
961 PyObject *args;
963 typedef struct {
964 PyObject *seq;
965 PySequenceMethods *sqf;
966 int len;
967 } sequence;
969 PyObject *func, *result;
970 sequence *seqs = NULL, *sqp;
971 int n, len;
972 register int i, j;
974 n = PyTuple_Size(args);
975 if (n < 2) {
976 PyErr_SetString(PyExc_TypeError,
977 "map() requires at least two args");
978 return NULL;
981 func = PyTuple_GetItem(args, 0);
982 n--;
984 if (func == Py_None && n == 1) {
985 /* map(None, S) is the same as list(S). */
986 return PySequence_List(PyTuple_GetItem(args, 1));
989 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
990 PyErr_NoMemory();
991 goto Fail_2;
994 for (len = 0, i = 0, sqp = seqs; i < n; ++i, ++sqp) {
995 int curlen;
996 PySequenceMethods *sqf;
998 if ((sqp->seq = PyTuple_GetItem(args, i + 1)) == NULL)
999 goto Fail_2;
1001 sqp->sqf = sqf = sqp->seq->ob_type->tp_as_sequence;
1002 if (sqf == NULL ||
1003 sqf->sq_length == NULL ||
1004 sqf->sq_item == NULL)
1006 static char errmsg[] =
1007 "argument %d to map() must be a sequence object";
1008 char errbuf[sizeof(errmsg) + 25];
1010 sprintf(errbuf, errmsg, i+2);
1011 PyErr_SetString(PyExc_TypeError, errbuf);
1012 goto Fail_2;
1015 if ((curlen = sqp->len = (*sqp->sqf->sq_length)(sqp->seq)) < 0)
1016 goto Fail_2;
1018 if (curlen > len)
1019 len = curlen;
1022 if ((result = (PyObject *) PyList_New(len)) == NULL)
1023 goto Fail_2;
1025 for (i = 0; ; ++i) {
1026 PyObject *alist, *item=NULL, *value;
1027 int any = 0;
1029 if (func == Py_None && n == 1)
1030 alist = NULL;
1031 else {
1032 if ((alist = PyTuple_New(n)) == NULL)
1033 goto Fail_1;
1036 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
1037 if (sqp->len < 0) {
1038 Py_INCREF(Py_None);
1039 item = Py_None;
1041 else {
1042 item = (*sqp->sqf->sq_item)(sqp->seq, i);
1043 if (item == NULL) {
1044 if (PyErr_ExceptionMatches(
1045 PyExc_IndexError))
1047 PyErr_Clear();
1048 Py_INCREF(Py_None);
1049 item = Py_None;
1050 sqp->len = -1;
1052 else {
1053 goto Fail_0;
1056 else
1057 any = 1;
1060 if (!alist)
1061 break;
1062 if (PyTuple_SetItem(alist, j, item) < 0) {
1063 Py_DECREF(item);
1064 goto Fail_0;
1066 continue;
1068 Fail_0:
1069 Py_XDECREF(alist);
1070 goto Fail_1;
1073 if (!alist)
1074 alist = item;
1076 if (!any) {
1077 Py_DECREF(alist);
1078 break;
1081 if (func == Py_None)
1082 value = alist;
1083 else {
1084 value = PyEval_CallObject(func, alist);
1085 Py_DECREF(alist);
1086 if (value == NULL)
1087 goto Fail_1;
1089 if (i >= len) {
1090 int status = PyList_Append(result, value);
1091 Py_DECREF(value);
1092 if (status < 0)
1093 goto Fail_1;
1095 else {
1096 if (PyList_SetItem(result, i, value) < 0)
1097 goto Fail_1;
1101 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
1102 goto Fail_1;
1104 PyMem_DEL(seqs);
1105 return result;
1107 Fail_1:
1108 Py_DECREF(result);
1109 Fail_2:
1110 if (seqs) PyMem_DEL(seqs);
1111 return NULL;
1114 static char map_doc[] =
1115 "map(function, sequence[, sequence, ...]) -> list\n\
1117 Return a list of the results of applying the function to the items of\n\
1118 the argument sequence(s). If more than one sequence is given, the\n\
1119 function is called with an argument list consisting of the corresponding\n\
1120 item of each sequence, substituting None for missing values when not all\n\
1121 sequences have the same length. If the function is None, return a list of\n\
1122 the items of the sequence (or a list of tuples if more than one sequence).";
1125 static PyObject *
1126 builtin_setattr(self, args)
1127 PyObject *self;
1128 PyObject *args;
1130 PyObject *v;
1131 PyObject *name;
1132 PyObject *value;
1134 if (!PyArg_ParseTuple(args, "OSO:setattr", &v, &name, &value))
1135 return NULL;
1136 if (PyObject_SetAttr(v, name, value) != 0)
1137 return NULL;
1138 Py_INCREF(Py_None);
1139 return Py_None;
1142 static char setattr_doc[] =
1143 "setattr(object, name, value)\n\
1145 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1146 ``x.y = v''.";
1149 static PyObject *
1150 builtin_delattr(self, args)
1151 PyObject *self;
1152 PyObject *args;
1154 PyObject *v;
1155 PyObject *name;
1157 if (!PyArg_ParseTuple(args, "OS:delattr", &v, &name))
1158 return NULL;
1159 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1160 return NULL;
1161 Py_INCREF(Py_None);
1162 return Py_None;
1165 static char delattr_doc[] =
1166 "delattr(object, name)\n\
1168 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1169 ``del x.y''.";
1172 static PyObject *
1173 builtin_hash(self, args)
1174 PyObject *self;
1175 PyObject *args;
1177 PyObject *v;
1178 long x;
1180 if (!PyArg_ParseTuple(args, "O:hash", &v))
1181 return NULL;
1182 x = PyObject_Hash(v);
1183 if (x == -1)
1184 return NULL;
1185 return PyInt_FromLong(x);
1188 static char hash_doc[] =
1189 "hash(object) -> integer\n\
1191 Return a hash value for the object. Two objects with the same value have\n\
1192 the same hash value. The reverse is not necessarily true, but likely.";
1195 static PyObject *
1196 builtin_hex(self, args)
1197 PyObject *self;
1198 PyObject *args;
1200 PyObject *v;
1201 PyNumberMethods *nb;
1203 if (!PyArg_ParseTuple(args, "O:hex", &v))
1204 return NULL;
1206 if ((nb = v->ob_type->tp_as_number) == NULL ||
1207 nb->nb_hex == NULL) {
1208 PyErr_SetString(PyExc_TypeError,
1209 "hex() argument can't be converted to hex");
1210 return NULL;
1212 return (*nb->nb_hex)(v);
1215 static char hex_doc[] =
1216 "hex(number) -> string\n\
1218 Return the hexadecimal representation of an integer or long integer.";
1221 static PyObject *builtin_raw_input Py_PROTO((PyObject *, PyObject *));
1223 static PyObject *
1224 builtin_input(self, args)
1225 PyObject *self;
1226 PyObject *args;
1228 PyObject *line;
1229 char *str;
1230 PyObject *res;
1231 PyObject *globals, *locals;
1233 line = builtin_raw_input(self, args);
1234 if (line == NULL)
1235 return line;
1236 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1237 return NULL;
1238 while (*str == ' ' || *str == '\t')
1239 str++;
1240 globals = PyEval_GetGlobals();
1241 locals = PyEval_GetLocals();
1242 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1243 if (PyDict_SetItemString(globals, "__builtins__",
1244 PyEval_GetBuiltins()) != 0)
1245 return NULL;
1247 res = PyRun_String(str, Py_eval_input, globals, locals);
1248 Py_DECREF(line);
1249 return res;
1252 static char input_doc[] =
1253 "input([prompt]) -> value\n\
1255 Equivalent to eval(raw_input(prompt)).";
1258 static PyObject *
1259 builtin_intern(self, args)
1260 PyObject *self;
1261 PyObject *args;
1263 PyObject *s;
1264 if (!PyArg_ParseTuple(args, "S:intern", &s))
1265 return NULL;
1266 Py_INCREF(s);
1267 PyString_InternInPlace(&s);
1268 return s;
1271 static char intern_doc[] =
1272 "intern(string) -> string\n\
1274 ``Intern'' the given string. This enters the string in the (global)\n\
1275 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1276 Return the string itself or the previously interned string object with the\n\
1277 same value.";
1280 static PyObject *
1281 builtin_int(self, args)
1282 PyObject *self;
1283 PyObject *args;
1285 PyObject *v;
1286 int base = -909; /* unlikely! */
1288 if (!PyArg_ParseTuple(args, "O|i:int", &v, &base))
1289 return NULL;
1290 if (base == -909)
1291 return PyNumber_Int(v);
1292 else if (!PyString_Check(v)) {
1293 PyErr_SetString(PyExc_TypeError,
1294 "can't convert non-string with explicit base");
1295 return NULL;
1297 return PyInt_FromString(PyString_AS_STRING(v), NULL, base);
1300 static char int_doc[] =
1301 "int(x[, base]) -> integer\n\
1303 Convert a string or number to an integer, if possible. A floating point\n\
1304 argument will be truncated towards zero (this does not include a string\n\
1305 representation of a floating point number!) When converting a string, use\n\
1306 the optional base. It is an error to supply a base when converting a\n\
1307 non-string.";
1310 static PyObject *
1311 builtin_long(self, args)
1312 PyObject *self;
1313 PyObject *args;
1315 PyObject *v;
1316 int base = -909; /* unlikely! */
1318 if (!PyArg_ParseTuple(args, "O|i:long", &v, &base))
1319 return NULL;
1320 if (base == -909)
1321 return PyNumber_Long(v);
1322 else if (!PyString_Check(v)) {
1323 PyErr_SetString(PyExc_TypeError,
1324 "can't convert non-string with explicit base");
1325 return NULL;
1327 return PyLong_FromString(PyString_AS_STRING(v), NULL, base);
1330 static char long_doc[] =
1331 "long(x) -> long integer\n\
1332 long(x, base) -> long integer\n\
1334 Convert a string or number to a long integer, if possible. A floating\n\
1335 point argument will be truncated towards zero (this does not include a\n\
1336 string representation of a floating point number!) When converting a\n\
1337 string, use the given base. It is an error to supply a base when\n\
1338 converting a non-string.";
1341 static PyObject *
1342 builtin_float(self, args)
1343 PyObject *self;
1344 PyObject *args;
1346 PyObject *v;
1348 if (!PyArg_ParseTuple(args, "O:float", &v))
1349 return NULL;
1350 if (PyString_Check(v))
1351 return PyFloat_FromString(v, NULL);
1352 return PyNumber_Float(v);
1355 static char float_doc[] =
1356 "float(x) -> floating point number\n\
1358 Convert a string or number to a floating point number, if possible.";
1361 static PyObject *
1362 builtin_len(self, args)
1363 PyObject *self;
1364 PyObject *args;
1366 PyObject *v;
1367 long res;
1369 if (!PyArg_ParseTuple(args, "O:len", &v))
1370 return NULL;
1371 res = PyObject_Length(v);
1372 if (res < 0 && PyErr_Occurred())
1373 return NULL;
1374 return PyInt_FromLong(res);
1377 static char len_doc[] =
1378 "len(object) -> integer\n\
1380 Return the number of items of a sequence or mapping.";
1383 static PyObject *
1384 builtin_list(self, args)
1385 PyObject *self;
1386 PyObject *args;
1388 PyObject *v;
1390 if (!PyArg_ParseTuple(args, "O:list", &v))
1391 return NULL;
1392 return PySequence_List(v);
1395 static char list_doc[] =
1396 "list(sequence) -> list\n\
1398 Return a new list whose items are the same as those of the argument sequence.";
1401 static PyObject *
1402 builtin_slice(self, args)
1403 PyObject *self;
1404 PyObject *args;
1406 PyObject *start, *stop, *step;
1408 start = stop = step = NULL;
1410 if (!PyArg_ParseTuple(args, "O|OO:slice", &start, &stop, &step))
1411 return NULL;
1413 /* This swapping of stop and start is to maintain similarity with
1414 range(). */
1415 if (stop == NULL) {
1416 stop = start;
1417 start = NULL;
1419 return PySlice_New(start, stop, step);
1422 static char slice_doc[] =
1423 "slice([start,] stop[, step]) -> slice object\n\
1425 Create a slice object. This is used for slicing by the Numeric extensions.";
1428 static PyObject *
1429 builtin_locals(self, args)
1430 PyObject *self;
1431 PyObject *args;
1433 PyObject *d;
1435 if (!PyArg_ParseTuple(args, ":locals"))
1436 return NULL;
1437 d = PyEval_GetLocals();
1438 Py_INCREF(d);
1439 return d;
1442 static char locals_doc[] =
1443 "locals() -> dictionary\n\
1445 Return the dictionary containing the current scope's local variables.";
1448 static PyObject *
1449 min_max(args, sign)
1450 PyObject *args;
1451 int sign;
1453 int i;
1454 PyObject *v, *w, *x;
1455 PySequenceMethods *sq;
1457 if (PyTuple_Size(args) > 1)
1458 v = args;
1459 else if (!PyArg_ParseTuple(args, "O:min/max", &v))
1460 return NULL;
1461 sq = v->ob_type->tp_as_sequence;
1462 if (sq == NULL || sq->sq_item == NULL) {
1463 PyErr_SetString(PyExc_TypeError,
1464 "min() or max() of non-sequence");
1465 return NULL;
1467 w = NULL;
1468 for (i = 0; ; i++) {
1469 x = (*sq->sq_item)(v, i); /* Implies INCREF */
1470 if (x == NULL) {
1471 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
1472 PyErr_Clear();
1473 break;
1475 Py_XDECREF(w);
1476 return NULL;
1478 if (w == NULL)
1479 w = x;
1480 else {
1481 int c = PyObject_Compare(x, w);
1482 if (c && PyErr_Occurred()) {
1483 Py_DECREF(x);
1484 Py_XDECREF(w);
1485 return NULL;
1487 if (c * sign > 0) {
1488 Py_DECREF(w);
1489 w = x;
1491 else
1492 Py_DECREF(x);
1495 if (w == NULL)
1496 PyErr_SetString(PyExc_ValueError,
1497 "min() or max() of empty sequence");
1498 return w;
1501 static PyObject *
1502 builtin_min(self, v)
1503 PyObject *self;
1504 PyObject *v;
1506 return min_max(v, -1);
1509 static char min_doc[] =
1510 "min(sequence) -> value\n\
1511 min(a, b, c, ...) -> value\n\
1513 With a single sequence argument, return its smallest item.\n\
1514 With two or more arguments, return the smallest argument.";
1517 static PyObject *
1518 builtin_max(self, v)
1519 PyObject *self;
1520 PyObject *v;
1522 return min_max(v, 1);
1525 static char max_doc[] =
1526 "max(sequence) -> value\n\
1527 max(a, b, c, ...) -> value\n\
1529 With a single sequence argument, return its largest item.\n\
1530 With two or more arguments, return the largest argument.";
1533 static PyObject *
1534 builtin_oct(self, args)
1535 PyObject *self;
1536 PyObject *args;
1538 PyObject *v;
1539 PyNumberMethods *nb;
1541 if (!PyArg_ParseTuple(args, "O:oct", &v))
1542 return NULL;
1543 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1544 nb->nb_oct == NULL) {
1545 PyErr_SetString(PyExc_TypeError,
1546 "oct() argument can't be converted to oct");
1547 return NULL;
1549 return (*nb->nb_oct)(v);
1552 static char oct_doc[] =
1553 "oct(number) -> string\n\
1555 Return the octal representation of an integer or long integer.";
1558 static PyObject *
1559 builtin_open(self, args)
1560 PyObject *self;
1561 PyObject *args;
1563 char *name;
1564 char *mode = "r";
1565 int bufsize = -1;
1566 PyObject *f;
1568 if (!PyArg_ParseTuple(args, "s|si:open", &name, &mode, &bufsize))
1569 return NULL;
1570 f = PyFile_FromString(name, mode);
1571 if (f != NULL)
1572 PyFile_SetBufSize(f, bufsize);
1573 return f;
1576 static char open_doc[] =
1577 "open(filename[, mode[, buffering]]) -> file object\n\
1579 Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n\
1580 writing or appending. The file will be created if it doesn't exist\n\
1581 when opened for writing or appending; it will be truncated when\n\
1582 opened for writing. Add a 'b' to the mode for binary files.\n\
1583 Add a '+' to the mode to allow simultaneous reading and writing.\n\
1584 If the buffering argument is given, 0 means unbuffered, 1 means line\n\
1585 buffered, and larger numbers specify the buffer size.";
1588 static PyObject *
1589 builtin_ord(self, args)
1590 PyObject *self;
1591 PyObject *args;
1593 PyObject *obj;
1594 long ord;
1596 if (!PyArg_ParseTuple(args, "O:ord", &obj))
1597 return NULL;
1599 if (PyString_Check(obj) && PyString_GET_SIZE(obj) == 1)
1600 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1601 else if (PyUnicode_Check(obj) && PyUnicode_GET_SIZE(obj) == 1)
1602 ord = (long)*PyUnicode_AS_UNICODE(obj);
1603 else {
1604 PyErr_SetString(PyExc_TypeError,
1605 "expected a string or unicode character");
1606 return NULL;
1609 return PyInt_FromLong(ord);
1612 static char ord_doc[] =
1613 "ord(c) -> integer\n\
1615 Return the integer ordinal of a one character [unicode] string.";
1618 static PyObject *
1619 builtin_pow(self, args)
1620 PyObject *self;
1621 PyObject *args;
1623 PyObject *v, *w, *z = Py_None;
1625 if (!PyArg_ParseTuple(args, "OO|O:pow", &v, &w, &z))
1626 return NULL;
1627 return PyNumber_Power(v, w, z);
1630 static char pow_doc[] =
1631 "pow(x, y[, z]) -> number\n\
1633 With two arguments, equivalent to x**y. With three arguments,\n\
1634 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).";
1637 /* Return number of items in range/xrange (lo, hi, step). step > 0
1638 * required. Return a value < 0 if & only if the true value is too
1639 * large to fit in a signed long.
1641 static long
1642 get_len_of_range(lo, hi, step)
1643 long lo;
1644 long hi;
1645 long step; /* must be > 0 */
1647 /* -------------------------------------------------------------
1648 If lo >= hi, the range is empty.
1649 Else if n values are in the range, the last one is
1650 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1651 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1652 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1653 the RHS is non-negative and so truncation is the same as the
1654 floor. Letting M be the largest positive long, the worst case
1655 for the RHS numerator is hi=M, lo=-M-1, and then
1656 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1657 precision to compute the RHS exactly.
1658 ---------------------------------------------------------------*/
1659 long n = 0;
1660 if (lo < hi) {
1661 unsigned long uhi = (unsigned long)hi;
1662 unsigned long ulo = (unsigned long)lo;
1663 unsigned long diff = uhi - ulo - 1;
1664 n = (long)(diff / (unsigned long)step + 1);
1666 return n;
1669 static PyObject *
1670 builtin_range(self, args)
1671 PyObject *self;
1672 PyObject *args;
1674 long ilow = 0, ihigh = 0, istep = 1;
1675 long bign;
1676 int i, n;
1678 PyObject *v;
1680 if (PyTuple_Size(args) <= 1) {
1681 if (!PyArg_ParseTuple(args,
1682 "l;range() requires 1-3 int arguments",
1683 &ihigh))
1684 return NULL;
1686 else {
1687 if (!PyArg_ParseTuple(args,
1688 "ll|l;range() requires 1-3 int arguments",
1689 &ilow, &ihigh, &istep))
1690 return NULL;
1692 if (istep == 0) {
1693 PyErr_SetString(PyExc_ValueError, "zero step for range()");
1694 return NULL;
1696 if (istep > 0)
1697 bign = get_len_of_range(ilow, ihigh, istep);
1698 else
1699 bign = get_len_of_range(ihigh, ilow, -istep);
1700 n = (int)bign;
1701 if (bign < 0 || (long)n != bign) {
1702 PyErr_SetString(PyExc_OverflowError,
1703 "range() has too many items");
1704 return NULL;
1706 v = PyList_New(n);
1707 if (v == NULL)
1708 return NULL;
1709 for (i = 0; i < n; i++) {
1710 PyObject *w = PyInt_FromLong(ilow);
1711 if (w == NULL) {
1712 Py_DECREF(v);
1713 return NULL;
1715 PyList_SET_ITEM(v, i, w);
1716 ilow += istep;
1718 return v;
1721 static char range_doc[] =
1722 "range([start,] stop[, step]) -> list of integers\n\
1724 Return a list containing an arithmetic progression of integers.\n\
1725 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1726 When step is given, it specifies the increment (or decrement).\n\
1727 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1728 These are exactly the valid indices for a list of 4 elements.";
1731 static PyObject *
1732 builtin_xrange(self, args)
1733 PyObject *self;
1734 PyObject *args;
1736 long ilow = 0, ihigh = 0, istep = 1;
1737 long n;
1739 if (PyTuple_Size(args) <= 1) {
1740 if (!PyArg_ParseTuple(args,
1741 "l;xrange() requires 1-3 int arguments",
1742 &ihigh))
1743 return NULL;
1745 else {
1746 if (!PyArg_ParseTuple(args,
1747 "ll|l;xrange() requires 1-3 int arguments",
1748 &ilow, &ihigh, &istep))
1749 return NULL;
1751 if (istep == 0) {
1752 PyErr_SetString(PyExc_ValueError, "zero step for xrange()");
1753 return NULL;
1755 if (istep > 0)
1756 n = get_len_of_range(ilow, ihigh, istep);
1757 else
1758 n = get_len_of_range(ihigh, ilow, -istep);
1759 if (n < 0) {
1760 PyErr_SetString(PyExc_OverflowError,
1761 "xrange() has more than sys.maxint items");
1762 return NULL;
1764 return PyRange_New(ilow, n, istep, 1);
1767 static char xrange_doc[] =
1768 "xrange([start,] stop[, step]) -> xrange object\n\
1770 Like range(), but instead of returning a list, returns an object that\n\
1771 generates the numbers in the range on demand. This is slightly slower\n\
1772 than range() but more memory efficient.";
1775 static PyObject *
1776 builtin_raw_input(self, args)
1777 PyObject *self;
1778 PyObject *args;
1780 PyObject *v = NULL;
1781 PyObject *f;
1783 if (!PyArg_ParseTuple(args, "|O:[raw_]input", &v))
1784 return NULL;
1785 if (PyFile_AsFile(PySys_GetObject("stdin")) == stdin &&
1786 PyFile_AsFile(PySys_GetObject("stdout")) == stdout &&
1787 isatty(fileno(stdin)) && isatty(fileno(stdout))) {
1788 PyObject *po;
1789 char *prompt;
1790 char *s;
1791 PyObject *result;
1792 if (v != NULL) {
1793 po = PyObject_Str(v);
1794 if (po == NULL)
1795 return NULL;
1796 prompt = PyString_AsString(po);
1797 if (prompt == NULL)
1798 return NULL;
1800 else {
1801 po = NULL;
1802 prompt = "";
1804 s = PyOS_Readline(prompt);
1805 Py_XDECREF(po);
1806 if (s == NULL) {
1807 PyErr_SetNone(PyExc_KeyboardInterrupt);
1808 return NULL;
1810 if (*s == '\0') {
1811 PyErr_SetNone(PyExc_EOFError);
1812 result = NULL;
1814 else { /* strip trailing '\n' */
1815 result = PyString_FromStringAndSize(s, strlen(s)-1);
1817 free(s);
1818 return result;
1820 if (v != NULL) {
1821 f = PySys_GetObject("stdout");
1822 if (f == NULL) {
1823 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1824 return NULL;
1826 if (Py_FlushLine() != 0 ||
1827 PyFile_WriteObject(v, f, Py_PRINT_RAW) != 0)
1828 return NULL;
1830 f = PySys_GetObject("stdin");
1831 if (f == NULL) {
1832 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdin");
1833 return NULL;
1835 return PyFile_GetLine(f, -1);
1838 static char raw_input_doc[] =
1839 "raw_input([prompt]) -> string\n\
1841 Read a string from standard input. The trailing newline is stripped.\n\
1842 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1843 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1844 is printed without a trailing newline before reading.";
1847 static PyObject *
1848 builtin_reduce(self, args)
1849 PyObject *self;
1850 PyObject *args;
1852 PyObject *seq, *func, *result = NULL;
1853 PySequenceMethods *sqf;
1854 register int i;
1856 if (!PyArg_ParseTuple(args, "OO|O:reduce", &func, &seq, &result))
1857 return NULL;
1858 if (result != NULL)
1859 Py_INCREF(result);
1861 sqf = seq->ob_type->tp_as_sequence;
1862 if (sqf == NULL || sqf->sq_item == NULL) {
1863 PyErr_SetString(PyExc_TypeError,
1864 "2nd argument to reduce() must be a sequence object");
1865 return NULL;
1868 if ((args = PyTuple_New(2)) == NULL)
1869 goto Fail;
1871 for (i = 0; ; ++i) {
1872 PyObject *op2;
1874 if (args->ob_refcnt > 1) {
1875 Py_DECREF(args);
1876 if ((args = PyTuple_New(2)) == NULL)
1877 goto Fail;
1880 if ((op2 = (*sqf->sq_item)(seq, i)) == NULL) {
1881 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
1882 PyErr_Clear();
1883 break;
1885 goto Fail;
1888 if (result == NULL)
1889 result = op2;
1890 else {
1891 PyTuple_SetItem(args, 0, result);
1892 PyTuple_SetItem(args, 1, op2);
1893 if ((result = PyEval_CallObject(func, args)) == NULL)
1894 goto Fail;
1898 Py_DECREF(args);
1900 if (result == NULL)
1901 PyErr_SetString(PyExc_TypeError,
1902 "reduce of empty sequence with no initial value");
1904 return result;
1906 Fail:
1907 Py_XDECREF(args);
1908 Py_XDECREF(result);
1909 return NULL;
1912 static char reduce_doc[] =
1913 "reduce(function, sequence[, initial]) -> value\n\
1915 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1916 from left to right, so as to reduce the sequence to a single value.\n\
1917 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1918 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1919 of the sequence in the calculation, and serves as a default when the\n\
1920 sequence is empty.";
1923 static PyObject *
1924 builtin_reload(self, args)
1925 PyObject *self;
1926 PyObject *args;
1928 PyObject *v;
1930 if (!PyArg_ParseTuple(args, "O:reload", &v))
1931 return NULL;
1932 return PyImport_ReloadModule(v);
1935 static char reload_doc[] =
1936 "reload(module) -> module\n\
1938 Reload the module. The module must have been successfully imported before.";
1941 static PyObject *
1942 builtin_repr(self, args)
1943 PyObject *self;
1944 PyObject *args;
1946 PyObject *v;
1948 if (!PyArg_ParseTuple(args, "O:repr", &v))
1949 return NULL;
1950 return PyObject_Repr(v);
1953 static char repr_doc[] =
1954 "repr(object) -> string\n\
1956 Return the canonical string representation of the object.\n\
1957 For most object types, eval(repr(object)) == object.";
1960 static PyObject *
1961 builtin_round(self, args)
1962 PyObject *self;
1963 PyObject *args;
1965 double x;
1966 double f;
1967 int ndigits = 0;
1968 int i;
1970 if (!PyArg_ParseTuple(args, "d|i:round", &x, &ndigits))
1971 return NULL;
1972 f = 1.0;
1973 i = abs(ndigits);
1974 while (--i >= 0)
1975 f = f*10.0;
1976 if (ndigits < 0)
1977 x /= f;
1978 else
1979 x *= f;
1980 if (x >= 0.0)
1981 x = floor(x + 0.5);
1982 else
1983 x = ceil(x - 0.5);
1984 if (ndigits < 0)
1985 x *= f;
1986 else
1987 x /= f;
1988 return PyFloat_FromDouble(x);
1991 static char round_doc[] =
1992 "round(number[, ndigits]) -> floating point number\n\
1994 Round a number to a given precision in decimal digits (default 0 digits).\n\
1995 This always returns a floating point number. Precision may be negative.";
1998 static PyObject *
1999 builtin_str(self, args)
2000 PyObject *self;
2001 PyObject *args;
2003 PyObject *v;
2005 if (!PyArg_ParseTuple(args, "O:str", &v))
2006 return NULL;
2007 return PyObject_Str(v);
2010 static char str_doc[] =
2011 "str(object) -> string\n\
2013 Return a nice string representation of the object.\n\
2014 If the argument is a string, the return value is the same object.";
2017 static PyObject *
2018 builtin_tuple(self, args)
2019 PyObject *self;
2020 PyObject *args;
2022 PyObject *v;
2024 if (!PyArg_ParseTuple(args, "O:tuple", &v))
2025 return NULL;
2026 return PySequence_Tuple(v);
2029 static char tuple_doc[] =
2030 "tuple(sequence) -> list\n\
2032 Return a tuple whose items are the same as those of the argument sequence.\n\
2033 If the argument is a tuple, the return value is the same object.";
2036 static PyObject *
2037 builtin_type(self, args)
2038 PyObject *self;
2039 PyObject *args;
2041 PyObject *v;
2043 if (!PyArg_ParseTuple(args, "O:type", &v))
2044 return NULL;
2045 v = (PyObject *)v->ob_type;
2046 Py_INCREF(v);
2047 return v;
2050 static char type_doc[] =
2051 "type(object) -> type object\n\
2053 Return the type of the object.";
2056 static PyObject *
2057 builtin_vars(self, args)
2058 PyObject *self;
2059 PyObject *args;
2061 PyObject *v = NULL;
2062 PyObject *d;
2064 if (!PyArg_ParseTuple(args, "|O:vars", &v))
2065 return NULL;
2066 if (v == NULL) {
2067 d = PyEval_GetLocals();
2068 if (d == NULL) {
2069 if (!PyErr_Occurred())
2070 PyErr_SetString(PyExc_SystemError,
2071 "no locals!?");
2073 else
2074 Py_INCREF(d);
2076 else {
2077 d = PyObject_GetAttrString(v, "__dict__");
2078 if (d == NULL) {
2079 PyErr_SetString(PyExc_TypeError,
2080 "vars() argument must have __dict__ attribute");
2081 return NULL;
2084 return d;
2087 static char vars_doc[] =
2088 "vars([object]) -> dictionary\n\
2090 Without arguments, equivalent to locals().\n\
2091 With an argument, equivalent to object.__dict__.";
2093 static int
2094 abstract_issubclass(derived, cls, err, first)
2095 PyObject *derived;
2096 PyObject *cls;
2097 char *err;
2098 int first;
2100 static PyObject *__bases__ = NULL;
2101 PyObject *bases;
2102 int i, n;
2103 int r = 0;
2105 if (__bases__ == NULL) {
2106 __bases__ = PyString_FromString("__bases__");
2107 if (__bases__ == NULL)
2108 return -1;
2111 if (first) {
2112 bases = PyObject_GetAttr(cls, __bases__);
2113 if (bases == NULL || !PyTuple_Check(bases)) {
2114 Py_XDECREF(bases);
2115 PyErr_SetString(PyExc_TypeError, err);
2116 return -1;
2118 Py_DECREF(bases);
2121 if (derived == cls)
2122 return 1;
2124 bases = PyObject_GetAttr(derived, __bases__);
2125 if (bases == NULL || !PyTuple_Check(bases)) {
2126 Py_XDECREF(bases);
2127 PyErr_SetString(PyExc_TypeError, err);
2128 return -1;
2131 n = PyTuple_GET_SIZE(bases);
2132 for (i = 0; i < n; i++) {
2133 r = abstract_issubclass(PyTuple_GET_ITEM(bases, i),
2134 cls, err, 0);
2135 if (r != 0)
2136 break;
2139 Py_DECREF(bases);
2141 return r;
2144 static PyObject *
2145 builtin_isinstance(self, args)
2146 PyObject *self;
2147 PyObject *args;
2149 PyObject *inst;
2150 PyObject *cls;
2151 PyObject *icls;
2152 static PyObject *__class__ = NULL;
2153 int retval = 0;
2155 if (!PyArg_ParseTuple(args, "OO:isinstance", &inst, &cls))
2156 return NULL;
2158 if (PyClass_Check(cls)) {
2159 if (PyInstance_Check(inst)) {
2160 PyObject *inclass =
2161 (PyObject*)((PyInstanceObject*)inst)->in_class;
2162 retval = PyClass_IsSubclass(inclass, cls);
2165 else if (PyType_Check(cls)) {
2166 retval = ((PyObject *)(inst->ob_type) == cls);
2168 else if (!PyInstance_Check(inst)) {
2169 if (__class__ == NULL) {
2170 __class__ = PyString_FromString("__class__");
2171 if (__class__ == NULL)
2172 return NULL;
2174 icls = PyObject_GetAttr(inst, __class__);
2175 if (icls != NULL) {
2176 retval = abstract_issubclass(
2177 icls, cls,
2178 "second argument must be a class",
2180 Py_DECREF(icls);
2181 if (retval < 0)
2182 return NULL;
2184 else {
2185 PyErr_SetString(PyExc_TypeError,
2186 "second argument must be a class");
2187 return NULL;
2190 else {
2191 PyErr_SetString(PyExc_TypeError,
2192 "second argument must be a class");
2193 return NULL;
2195 return PyInt_FromLong(retval);
2198 static char isinstance_doc[] =
2199 "isinstance(object, class-or-type) -> Boolean\n\
2201 Return whether an object is an instance of a class or of a subclass thereof.\n\
2202 With a type as second argument, return whether that is the object's type.";
2205 static PyObject *
2206 builtin_issubclass(self, args)
2207 PyObject *self;
2208 PyObject *args;
2210 PyObject *derived;
2211 PyObject *cls;
2212 int retval;
2214 if (!PyArg_ParseTuple(args, "OO:issubclass", &derived, &cls))
2215 return NULL;
2217 if (!PyClass_Check(derived) || !PyClass_Check(cls)) {
2218 retval = abstract_issubclass(
2219 derived, cls, "arguments must be classes", 1);
2220 if (retval < 0)
2221 return NULL;
2223 else {
2224 /* shortcut */
2225 if (!(retval = (derived == cls)))
2226 retval = PyClass_IsSubclass(derived, cls);
2229 return PyInt_FromLong(retval);
2232 static char issubclass_doc[] =
2233 "issubclass(C, B) -> Boolean\n\
2235 Return whether class C is a subclass (i.e., a derived class) of class B.";
2238 static PyMethodDef builtin_methods[] = {
2239 {"__import__", builtin___import__, 1, import_doc},
2240 {"abs", builtin_abs, 1, abs_doc},
2241 {"apply", builtin_apply, 1, apply_doc},
2242 {"buffer", builtin_buffer, 1, buffer_doc},
2243 {"callable", builtin_callable, 1, callable_doc},
2244 {"chr", builtin_chr, 1, chr_doc},
2245 {"cmp", builtin_cmp, 1, cmp_doc},
2246 {"coerce", builtin_coerce, 1, coerce_doc},
2247 {"compile", builtin_compile, 1, compile_doc},
2248 #ifndef WITHOUT_COMPLEX
2249 {"complex", builtin_complex, 1, complex_doc},
2250 #endif
2251 {"delattr", builtin_delattr, 1, delattr_doc},
2252 {"dir", builtin_dir, 1, dir_doc},
2253 {"divmod", builtin_divmod, 1, divmod_doc},
2254 {"eval", builtin_eval, 1, eval_doc},
2255 {"execfile", builtin_execfile, 1, execfile_doc},
2256 {"filter", builtin_filter, 1, filter_doc},
2257 {"float", builtin_float, 1, float_doc},
2258 {"getattr", builtin_getattr, 1, getattr_doc},
2259 {"globals", builtin_globals, 1, globals_doc},
2260 {"hasattr", builtin_hasattr, 1, hasattr_doc},
2261 {"hash", builtin_hash, 1, hash_doc},
2262 {"hex", builtin_hex, 1, hex_doc},
2263 {"id", builtin_id, 1, id_doc},
2264 {"input", builtin_input, 1, input_doc},
2265 {"intern", builtin_intern, 1, intern_doc},
2266 {"int", builtin_int, 1, int_doc},
2267 {"isinstance", builtin_isinstance, 1, isinstance_doc},
2268 {"issubclass", builtin_issubclass, 1, issubclass_doc},
2269 {"len", builtin_len, 1, len_doc},
2270 {"list", builtin_list, 1, list_doc},
2271 {"locals", builtin_locals, 1, locals_doc},
2272 {"long", builtin_long, 1, long_doc},
2273 {"map", builtin_map, 1, map_doc},
2274 {"max", builtin_max, 1, max_doc},
2275 {"min", builtin_min, 1, min_doc},
2276 {"oct", builtin_oct, 1, oct_doc},
2277 {"open", builtin_open, 1, open_doc},
2278 {"ord", builtin_ord, 1, ord_doc},
2279 {"pow", builtin_pow, 1, pow_doc},
2280 {"range", builtin_range, 1, range_doc},
2281 {"raw_input", builtin_raw_input, 1, raw_input_doc},
2282 {"reduce", builtin_reduce, 1, reduce_doc},
2283 {"reload", builtin_reload, 1, reload_doc},
2284 {"repr", builtin_repr, 1, repr_doc},
2285 {"round", builtin_round, 1, round_doc},
2286 {"setattr", builtin_setattr, 1, setattr_doc},
2287 {"slice", builtin_slice, 1, slice_doc},
2288 {"str", builtin_str, 1, str_doc},
2289 {"tuple", builtin_tuple, 1, tuple_doc},
2290 {"type", builtin_type, 1, type_doc},
2291 {"unicode", builtin_unicode, 1, unicode_doc},
2292 {"unichr", builtin_unichr, 1, unichr_doc},
2293 {"vars", builtin_vars, 1, vars_doc},
2294 {"xrange", builtin_xrange, 1, xrange_doc},
2295 {NULL, NULL},
2298 /* Predefined exceptions */
2300 PyObject *PyExc_Exception;
2301 PyObject *PyExc_StandardError;
2302 PyObject *PyExc_ArithmeticError;
2303 PyObject *PyExc_LookupError;
2305 PyObject *PyExc_AssertionError;
2306 PyObject *PyExc_AttributeError;
2307 PyObject *PyExc_EOFError;
2308 PyObject *PyExc_FloatingPointError;
2309 PyObject *PyExc_EnvironmentError;
2310 PyObject *PyExc_IOError;
2311 PyObject *PyExc_OSError;
2312 PyObject *PyExc_ImportError;
2313 PyObject *PyExc_IndexError;
2314 PyObject *PyExc_KeyError;
2315 PyObject *PyExc_KeyboardInterrupt;
2316 PyObject *PyExc_MemoryError;
2317 PyObject *PyExc_NameError;
2318 PyObject *PyExc_OverflowError;
2319 PyObject *PyExc_RuntimeError;
2320 PyObject *PyExc_NotImplementedError;
2321 PyObject *PyExc_SyntaxError;
2322 PyObject *PyExc_SystemError;
2323 PyObject *PyExc_SystemExit;
2324 PyObject *PyExc_UnboundLocalError;
2325 PyObject *PyExc_UnicodeError;
2326 PyObject *PyExc_TypeError;
2327 PyObject *PyExc_ValueError;
2328 PyObject *PyExc_ZeroDivisionError;
2329 #ifdef MS_WINDOWS
2330 PyObject *PyExc_WindowsError;
2331 #endif
2333 PyObject *PyExc_MemoryErrorInst;
2335 static struct
2337 char* name;
2338 PyObject** exc;
2339 int leaf_exc;
2341 bltin_exc[] = {
2342 {"Exception", &PyExc_Exception, 0},
2343 {"StandardError", &PyExc_StandardError, 0},
2344 {"ArithmeticError", &PyExc_ArithmeticError, 0},
2345 {"LookupError", &PyExc_LookupError, 0},
2346 {"AssertionError", &PyExc_AssertionError, 1},
2347 {"AttributeError", &PyExc_AttributeError, 1},
2348 {"EOFError", &PyExc_EOFError, 1},
2349 {"FloatingPointError", &PyExc_FloatingPointError, 1},
2350 {"EnvironmentError", &PyExc_EnvironmentError, 0},
2351 {"IOError", &PyExc_IOError, 1},
2352 {"OSError", &PyExc_OSError, 1},
2353 {"ImportError", &PyExc_ImportError, 1},
2354 {"IndexError", &PyExc_IndexError, 1},
2355 {"KeyError", &PyExc_KeyError, 1},
2356 {"KeyboardInterrupt", &PyExc_KeyboardInterrupt, 1},
2357 {"MemoryError", &PyExc_MemoryError, 1},
2358 /* Note: NameError is not a leaf in exceptions.py, but unlike
2359 the other non-leafs NameError is meant to be raised directly
2360 at times -- the leaf_exc member really seems to mean something
2361 like "this is an abstract base class" when false.
2363 {"NameError", &PyExc_NameError, 1},
2364 {"OverflowError", &PyExc_OverflowError, 1},
2365 {"RuntimeError", &PyExc_RuntimeError, 1},
2366 {"NotImplementedError",&PyExc_NotImplementedError,1},
2367 {"SyntaxError", &PyExc_SyntaxError, 1},
2368 {"SystemError", &PyExc_SystemError, 1},
2369 {"SystemExit", &PyExc_SystemExit, 1},
2370 {"UnboundLocalError", &PyExc_UnboundLocalError, 1},
2371 {"UnicodeError", &PyExc_UnicodeError, 1},
2372 {"TypeError", &PyExc_TypeError, 1},
2373 {"ValueError", &PyExc_ValueError, 1},
2374 #ifdef MS_WINDOWS
2375 {"WindowsError", &PyExc_WindowsError, 1},
2376 #endif
2377 {"ZeroDivisionError", &PyExc_ZeroDivisionError, 1},
2378 {NULL, NULL}
2382 /* import exceptions module to extract class exceptions. on success,
2383 * return 1. on failure return 0 which signals _PyBuiltin_Init_2 to fall
2384 * back to using old-style string based exceptions.
2386 static int
2387 init_class_exc(dict)
2388 PyObject *dict;
2390 int i;
2391 PyObject *m = PyImport_ImportModule("exceptions");
2392 PyObject *args = NULL;
2393 PyObject *d = NULL;
2395 /* make sure we got the module and its dictionary */
2396 if (m == NULL ||
2397 (d = PyModule_GetDict(m)) == NULL)
2399 PySys_WriteStderr("'import exceptions' failed; ");
2400 if (Py_VerboseFlag) {
2401 PySys_WriteStderr("traceback:\n");
2402 PyErr_Print();
2404 else {
2405 PySys_WriteStderr("use -v for traceback\n");
2407 goto finally;
2409 for (i = 0; bltin_exc[i].name; i++) {
2410 /* dig the exception out of the module */
2411 PyObject *exc = PyDict_GetItemString(d, bltin_exc[i].name);
2412 if (!exc) {
2413 PySys_WriteStderr(
2414 "Built-in exception class not found: %s. Library mismatch?\n",
2415 bltin_exc[i].name);
2416 goto finally;
2418 /* free the old-style exception string object */
2419 Py_XDECREF(*bltin_exc[i].exc);
2421 /* squirrel away a pointer to the exception */
2422 Py_INCREF(exc);
2423 *bltin_exc[i].exc = exc;
2425 /* and insert the name in the __builtin__ module */
2426 if (PyDict_SetItemString(dict, bltin_exc[i].name, exc)) {
2427 PySys_WriteStderr(
2428 "Cannot insert exception into __builtin__: %s\n",
2429 bltin_exc[i].name);
2430 goto finally;
2434 /* we need one pre-allocated instance */
2435 args = Py_BuildValue("()");
2436 if (!args ||
2437 !(PyExc_MemoryErrorInst =
2438 PyEval_CallObject(PyExc_MemoryError, args)))
2440 PySys_WriteStderr("Cannot pre-allocate MemoryError instance\n");
2441 goto finally;
2443 Py_DECREF(args);
2445 /* we're done with the exceptions module */
2446 Py_DECREF(m);
2448 if (PyErr_Occurred()) {
2449 PySys_WriteStderr("Cannot initialize standard class exceptions; ");
2450 if (Py_VerboseFlag) {
2451 PySys_WriteStderr("traceback:\n");
2452 PyErr_Print();
2454 else
2455 PySys_WriteStderr("use -v for traceback\n");
2456 goto finally;
2458 return 1;
2459 finally:
2460 Py_XDECREF(m);
2461 Py_XDECREF(args);
2462 PyErr_Clear();
2463 return 0;
2467 static void
2468 fini_instances()
2470 Py_XDECREF(PyExc_MemoryErrorInst);
2471 PyExc_MemoryErrorInst = NULL;
2475 static PyObject *
2476 newstdexception(dict, name)
2477 PyObject *dict;
2478 char *name;
2480 PyObject *v = PyString_FromString(name);
2481 if (v == NULL || PyDict_SetItemString(dict, name, v) != 0)
2482 Py_FatalError("Cannot create string-based exceptions");
2483 return v;
2486 static void
2487 initerrors(dict)
2488 PyObject *dict;
2490 int i, j;
2491 int exccnt = 0;
2492 for (i = 0; bltin_exc[i].name; i++, exccnt++) {
2493 Py_XDECREF(*bltin_exc[i].exc);
2494 if (bltin_exc[i].leaf_exc)
2495 *bltin_exc[i].exc =
2496 newstdexception(dict, bltin_exc[i].name);
2499 /* This is kind of bogus because we special case the some of the
2500 * new exceptions to be nearly forward compatible. But this means
2501 * we hard code knowledge about exceptions.py into C here. I don't
2502 * have a better solution, though.
2504 PyExc_LookupError = PyTuple_New(2);
2505 Py_INCREF(PyExc_IndexError);
2506 PyTuple_SET_ITEM(PyExc_LookupError, 0, PyExc_IndexError);
2507 Py_INCREF(PyExc_KeyError);
2508 PyTuple_SET_ITEM(PyExc_LookupError, 1, PyExc_KeyError);
2509 PyDict_SetItemString(dict, "LookupError", PyExc_LookupError);
2511 PyExc_ArithmeticError = PyTuple_New(3);
2512 Py_INCREF(PyExc_OverflowError);
2513 PyTuple_SET_ITEM(PyExc_ArithmeticError, 0, PyExc_OverflowError);
2514 Py_INCREF(PyExc_ZeroDivisionError);
2515 PyTuple_SET_ITEM(PyExc_ArithmeticError, 1, PyExc_ZeroDivisionError);
2516 Py_INCREF(PyExc_FloatingPointError);
2517 PyTuple_SET_ITEM(PyExc_ArithmeticError, 2, PyExc_FloatingPointError);
2518 PyDict_SetItemString(dict, "ArithmeticError", PyExc_ArithmeticError);
2520 PyExc_EnvironmentError = PyTuple_New(2);
2521 Py_INCREF(PyExc_IOError);
2522 PyTuple_SET_ITEM(PyExc_EnvironmentError, 0, PyExc_IOError);
2523 Py_INCREF(PyExc_OSError);
2524 PyTuple_SET_ITEM(PyExc_EnvironmentError, 1, PyExc_OSError);
2525 PyDict_SetItemString(dict, "EnvironmentError", PyExc_EnvironmentError);
2527 /* Make UnboundLocalError an alias for NameError */
2528 Py_INCREF(PyExc_NameError);
2529 Py_DECREF(PyExc_UnboundLocalError);
2530 PyExc_UnboundLocalError = PyExc_NameError;
2531 if (PyDict_SetItemString(dict, "UnboundLocalError",
2532 PyExc_NameError) != 0)
2533 Py_FatalError("Cannot create string-based exceptions");
2535 /* Make UnicodeError an alias for ValueError */
2536 Py_INCREF(PyExc_ValueError);
2537 Py_DECREF(PyExc_UnicodeError);
2538 PyExc_UnicodeError = PyExc_ValueError;
2539 if (PyDict_SetItemString(dict, "UnicodeError",
2540 PyExc_ValueError) != 0)
2541 Py_FatalError("Cannot create string-based exceptions");
2543 /* missing from the StandardError tuple: Exception, StandardError,
2544 * and SystemExit
2546 PyExc_StandardError = PyTuple_New(exccnt-3);
2547 for (i = 2, j = 0; bltin_exc[i].name; i++) {
2548 PyObject *exc = *bltin_exc[i].exc;
2549 /* SystemExit is not an error, but it is an exception */
2550 if (exc != PyExc_SystemExit) {
2551 Py_INCREF(exc);
2552 PyTuple_SET_ITEM(PyExc_StandardError, j++, exc);
2555 PyDict_SetItemString(dict, "StandardError", PyExc_StandardError);
2557 /* Exception is a 2-tuple */
2558 PyExc_Exception = PyTuple_New(2);
2559 Py_INCREF(PyExc_SystemExit);
2560 PyTuple_SET_ITEM(PyExc_Exception, 0, PyExc_SystemExit);
2561 Py_INCREF(PyExc_StandardError);
2562 PyTuple_SET_ITEM(PyExc_Exception, 1, PyExc_StandardError);
2563 PyDict_SetItemString(dict, "Exception", PyExc_Exception);
2565 if (PyErr_Occurred())
2566 Py_FatalError("Could not initialize built-in string exceptions");
2570 static void
2571 finierrors()
2573 int i;
2574 for (i = 0; bltin_exc[i].name; i++) {
2575 PyObject *exc = *bltin_exc[i].exc;
2576 Py_XDECREF(exc);
2577 *bltin_exc[i].exc = NULL;
2581 static char builtin_doc[] =
2582 "Built-in functions, exceptions, and other objects.\n\
2584 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.";
2586 PyObject *
2587 _PyBuiltin_Init_1()
2589 PyObject *mod, *dict;
2590 mod = Py_InitModule4("__builtin__", builtin_methods,
2591 builtin_doc, (PyObject *)NULL,
2592 PYTHON_API_VERSION);
2593 if (mod == NULL)
2594 return NULL;
2595 dict = PyModule_GetDict(mod);
2596 initerrors(dict);
2597 if (PyDict_SetItemString(dict, "None", Py_None) < 0)
2598 return NULL;
2599 if (PyDict_SetItemString(dict, "Ellipsis", Py_Ellipsis) < 0)
2600 return NULL;
2601 if (PyDict_SetItemString(dict, "__debug__",
2602 PyInt_FromLong(Py_OptimizeFlag == 0)) < 0)
2603 return NULL;
2605 return mod;
2608 void
2609 _PyBuiltin_Init_2(dict)
2610 PyObject *dict;
2612 /* if Python was started with -X, initialize the class exceptions */
2613 if (Py_UseClassExceptionsFlag) {
2614 if (!init_class_exc(dict)) {
2615 /* class based exceptions could not be
2616 * initialized. Fall back to using string based
2617 * exceptions.
2619 PySys_WriteStderr(
2620 "Warning! Falling back to string-based exceptions\n");
2621 initerrors(dict);
2627 void
2628 _PyBuiltin_Fini_1()
2630 fini_instances();
2634 void
2635 _PyBuiltin_Fini_2()
2637 finierrors();
2641 /* Helper for filter(): filter a tuple through a function */
2643 static PyObject *
2644 filtertuple(func, tuple)
2645 PyObject *func;
2646 PyObject *tuple;
2648 PyObject *result;
2649 register int i, j;
2650 int len = PyTuple_Size(tuple);
2652 if (len == 0) {
2653 Py_INCREF(tuple);
2654 return tuple;
2657 if ((result = PyTuple_New(len)) == NULL)
2658 return NULL;
2660 for (i = j = 0; i < len; ++i) {
2661 PyObject *item, *good;
2662 int ok;
2664 if ((item = PyTuple_GetItem(tuple, i)) == NULL)
2665 goto Fail_1;
2666 if (func == Py_None) {
2667 Py_INCREF(item);
2668 good = item;
2670 else {
2671 PyObject *arg = Py_BuildValue("(O)", item);
2672 if (arg == NULL)
2673 goto Fail_1;
2674 good = PyEval_CallObject(func, arg);
2675 Py_DECREF(arg);
2676 if (good == NULL)
2677 goto Fail_1;
2679 ok = PyObject_IsTrue(good);
2680 Py_DECREF(good);
2681 if (ok) {
2682 Py_INCREF(item);
2683 if (PyTuple_SetItem(result, j++, item) < 0)
2684 goto Fail_1;
2688 if (_PyTuple_Resize(&result, j, 0) < 0)
2689 return NULL;
2691 return result;
2693 Fail_1:
2694 Py_DECREF(result);
2695 return NULL;
2699 /* Helper for filter(): filter a string through a function */
2701 static PyObject *
2702 filterstring(func, strobj)
2703 PyObject *func;
2704 PyObject *strobj;
2706 PyObject *result;
2707 register int i, j;
2708 int len = PyString_Size(strobj);
2710 if (func == Py_None) {
2711 /* No character is ever false -- share input string */
2712 Py_INCREF(strobj);
2713 return strobj;
2715 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2716 return NULL;
2718 for (i = j = 0; i < len; ++i) {
2719 PyObject *item, *arg, *good;
2720 int ok;
2722 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2723 if (item == NULL)
2724 goto Fail_1;
2725 arg = Py_BuildValue("(O)", item);
2726 Py_DECREF(item);
2727 if (arg == NULL)
2728 goto Fail_1;
2729 good = PyEval_CallObject(func, arg);
2730 Py_DECREF(arg);
2731 if (good == NULL)
2732 goto Fail_1;
2733 ok = PyObject_IsTrue(good);
2734 Py_DECREF(good);
2735 if (ok)
2736 PyString_AS_STRING((PyStringObject *)result)[j++] =
2737 PyString_AS_STRING((PyStringObject *)item)[0];
2740 if (j < len && _PyString_Resize(&result, j) < 0)
2741 return NULL;
2743 return result;
2745 Fail_1:
2746 Py_DECREF(result);
2747 return NULL;