Class around PixMap objects that allows more python-like access. By Joe Strout.
[python/dscho.git] / Python / bltinmodule.c
blob0340e3a2b5588eec2a81621b35744a3b716b2141
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,] step[, stop]) -> 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__.";
2007 static PyObject *
2008 builtin_isinstance(self, args)
2009 PyObject *self;
2010 PyObject *args;
2012 PyObject *inst;
2013 PyObject *cls;
2014 int retval;
2016 if (!PyArg_ParseTuple(args, "OO", &inst, &cls))
2017 return NULL;
2018 if (PyType_Check(cls)) {
2019 retval = ((PyObject *)(inst->ob_type) == cls);
2021 else {
2022 if (!PyClass_Check(cls)) {
2023 PyErr_SetString(PyExc_TypeError,
2024 "second argument must be a class");
2025 return NULL;
2028 if (!PyInstance_Check(inst))
2029 retval = 0;
2030 else {
2031 PyObject *inclass =
2032 (PyObject*)((PyInstanceObject*)inst)->in_class;
2033 retval = PyClass_IsSubclass(inclass, cls);
2036 return PyInt_FromLong(retval);
2039 static char isinstance_doc[] =
2040 "isinstance(object, class-or-type) -> Boolean\n\
2042 Return whether an object is an instance of a class or of a subclass thereof.\n\
2043 With a type as second argument, return whether that is the object's type.";
2046 static PyObject *
2047 builtin_issubclass(self, args)
2048 PyObject *self;
2049 PyObject *args;
2051 PyObject *derived;
2052 PyObject *cls;
2053 int retval;
2055 if (!PyArg_ParseTuple(args, "OO", &derived, &cls))
2056 return NULL;
2057 if (!PyClass_Check(derived) || !PyClass_Check(cls)) {
2058 PyErr_SetString(PyExc_TypeError, "arguments must be classes");
2059 return NULL;
2061 /* shortcut */
2062 if (!(retval = (derived == cls)))
2063 retval = PyClass_IsSubclass(derived, cls);
2065 return PyInt_FromLong(retval);
2068 static char issubclass_doc[] =
2069 "issubclass(C, B) -> Boolean\n\
2071 Return whether class C is a subclass (i.e., a derived class) of class B.";
2074 static PyMethodDef builtin_methods[] = {
2075 {"__import__", builtin___import__, 1, import_doc},
2076 {"abs", builtin_abs, 1, abs_doc},
2077 {"apply", builtin_apply, 1, apply_doc},
2078 {"buffer", builtin_buffer, 1, buffer_doc},
2079 {"callable", builtin_callable, 1, callable_doc},
2080 {"chr", builtin_chr, 1, chr_doc},
2081 {"cmp", builtin_cmp, 1, cmp_doc},
2082 {"coerce", builtin_coerce, 1, coerce_doc},
2083 {"compile", builtin_compile, 1, compile_doc},
2084 #ifndef WITHOUT_COMPLEX
2085 {"complex", builtin_complex, 1, complex_doc},
2086 #endif
2087 {"delattr", builtin_delattr, 1, delattr_doc},
2088 {"dir", builtin_dir, 1, dir_doc},
2089 {"divmod", builtin_divmod, 1, divmod_doc},
2090 {"eval", builtin_eval, 1, eval_doc},
2091 {"execfile", builtin_execfile, 1, execfile_doc},
2092 {"filter", builtin_filter, 1, filter_doc},
2093 {"float", builtin_float, 1, float_doc},
2094 {"getattr", builtin_getattr, 1, getattr_doc},
2095 {"globals", builtin_globals, 1, globals_doc},
2096 {"hasattr", builtin_hasattr, 1, hasattr_doc},
2097 {"hash", builtin_hash, 1, hash_doc},
2098 {"hex", builtin_hex, 1, hex_doc},
2099 {"id", builtin_id, 1, id_doc},
2100 {"input", builtin_input, 1, input_doc},
2101 {"intern", builtin_intern, 1, intern_doc},
2102 {"int", builtin_int, 1, int_doc},
2103 {"isinstance", builtin_isinstance, 1, isinstance_doc},
2104 {"issubclass", builtin_issubclass, 1, issubclass_doc},
2105 {"len", builtin_len, 1, len_doc},
2106 {"list", builtin_list, 1, list_doc},
2107 {"locals", builtin_locals, 1, locals_doc},
2108 {"long", builtin_long, 1, long_doc},
2109 {"map", builtin_map, 1, map_doc},
2110 {"max", builtin_max, 1, max_doc},
2111 {"min", builtin_min, 1, min_doc},
2112 {"oct", builtin_oct, 1, oct_doc},
2113 {"open", builtin_open, 1, open_doc},
2114 {"ord", builtin_ord, 1, ord_doc},
2115 {"pow", builtin_pow, 1, pow_doc},
2116 {"range", builtin_range, 1, range_doc},
2117 {"raw_input", builtin_raw_input, 1, raw_input_doc},
2118 {"reduce", builtin_reduce, 1, reduce_doc},
2119 {"reload", builtin_reload, 1, reload_doc},
2120 {"repr", builtin_repr, 1, repr_doc},
2121 {"round", builtin_round, 1, round_doc},
2122 {"setattr", builtin_setattr, 1, setattr_doc},
2123 {"slice", builtin_slice, 1, slice_doc},
2124 {"str", builtin_str, 1, str_doc},
2125 {"tuple", builtin_tuple, 1, tuple_doc},
2126 {"type", builtin_type, 1, type_doc},
2127 {"vars", builtin_vars, 1, vars_doc},
2128 {"xrange", builtin_xrange, 1, xrange_doc},
2129 {NULL, NULL},
2132 /* Predefined exceptions */
2134 PyObject *PyExc_Exception;
2135 PyObject *PyExc_StandardError;
2136 PyObject *PyExc_ArithmeticError;
2137 PyObject *PyExc_LookupError;
2139 PyObject *PyExc_AssertionError;
2140 PyObject *PyExc_AttributeError;
2141 PyObject *PyExc_EOFError;
2142 PyObject *PyExc_FloatingPointError;
2143 PyObject *PyExc_EnvironmentError;
2144 PyObject *PyExc_IOError;
2145 PyObject *PyExc_OSError;
2146 PyObject *PyExc_ImportError;
2147 PyObject *PyExc_IndexError;
2148 PyObject *PyExc_KeyError;
2149 PyObject *PyExc_KeyboardInterrupt;
2150 PyObject *PyExc_MemoryError;
2151 PyObject *PyExc_NameError;
2152 PyObject *PyExc_OverflowError;
2153 PyObject *PyExc_RuntimeError;
2154 PyObject *PyExc_NotImplementedError;
2155 PyObject *PyExc_SyntaxError;
2156 PyObject *PyExc_SystemError;
2157 PyObject *PyExc_SystemExit;
2158 PyObject *PyExc_TypeError;
2159 PyObject *PyExc_ValueError;
2160 PyObject *PyExc_ZeroDivisionError;
2162 PyObject *PyExc_MemoryErrorInst;
2164 static struct
2166 char* name;
2167 PyObject** exc;
2168 int leaf_exc;
2170 bltin_exc[] = {
2171 {"Exception", &PyExc_Exception, 0},
2172 {"StandardError", &PyExc_StandardError, 0},
2173 {"ArithmeticError", &PyExc_ArithmeticError, 0},
2174 {"LookupError", &PyExc_LookupError, 0},
2175 {"AssertionError", &PyExc_AssertionError, 1},
2176 {"AttributeError", &PyExc_AttributeError, 1},
2177 {"EOFError", &PyExc_EOFError, 1},
2178 {"FloatingPointError", &PyExc_FloatingPointError, 1},
2179 {"EnvironmentError", &PyExc_EnvironmentError, 0},
2180 {"IOError", &PyExc_IOError, 1},
2181 {"OSError", &PyExc_OSError, 1},
2182 {"ImportError", &PyExc_ImportError, 1},
2183 {"IndexError", &PyExc_IndexError, 1},
2184 {"KeyError", &PyExc_KeyError, 1},
2185 {"KeyboardInterrupt", &PyExc_KeyboardInterrupt, 1},
2186 {"MemoryError", &PyExc_MemoryError, 1},
2187 {"NameError", &PyExc_NameError, 1},
2188 {"OverflowError", &PyExc_OverflowError, 1},
2189 {"RuntimeError", &PyExc_RuntimeError, 1},
2190 {"NotImplementedError",&PyExc_NotImplementedError,1},
2191 {"SyntaxError", &PyExc_SyntaxError, 1},
2192 {"SystemError", &PyExc_SystemError, 1},
2193 {"SystemExit", &PyExc_SystemExit, 1},
2194 {"TypeError", &PyExc_TypeError, 1},
2195 {"ValueError", &PyExc_ValueError, 1},
2196 {"ZeroDivisionError", &PyExc_ZeroDivisionError, 1},
2197 {NULL, NULL}
2201 /* import exceptions module to extract class exceptions. on success,
2202 * return 1. on failure return 0 which signals _PyBuiltin_Init_2 to fall
2203 * back to using old-style string based exceptions.
2205 static int
2206 init_class_exc(dict)
2207 PyObject *dict;
2209 int i;
2210 PyObject *m = PyImport_ImportModule("exceptions");
2211 PyObject *args = NULL;
2212 PyObject *d = NULL;
2214 /* make sure we got the module and its dictionary */
2215 if (m == NULL ||
2216 (d = PyModule_GetDict(m)) == NULL)
2218 PySys_WriteStderr("'import exceptions' failed; ");
2219 if (Py_VerboseFlag) {
2220 PySys_WriteStderr("traceback:\n");
2221 PyErr_Print();
2223 else {
2224 PySys_WriteStderr("use -v for traceback\n");
2226 goto finally;
2228 for (i = 0; bltin_exc[i].name; i++) {
2229 /* dig the exception out of the module */
2230 PyObject *exc = PyDict_GetItemString(d, bltin_exc[i].name);
2231 if (!exc) {
2232 PySys_WriteStderr(
2233 "Built-in exception class not found: %s. Library mismatch?\n",
2234 bltin_exc[i].name);
2235 goto finally;
2237 /* free the old-style exception string object */
2238 Py_XDECREF(*bltin_exc[i].exc);
2240 /* squirrel away a pointer to the exception */
2241 Py_INCREF(exc);
2242 *bltin_exc[i].exc = exc;
2244 /* and insert the name in the __builtin__ module */
2245 if (PyDict_SetItemString(dict, bltin_exc[i].name, exc)) {
2246 PySys_WriteStderr(
2247 "Cannot insert exception into __builtin__: %s\n",
2248 bltin_exc[i].name);
2249 goto finally;
2253 /* we need one pre-allocated instance */
2254 args = Py_BuildValue("()");
2255 if (!args ||
2256 !(PyExc_MemoryErrorInst =
2257 PyEval_CallObject(PyExc_MemoryError, args)))
2259 PySys_WriteStderr("Cannot pre-allocate MemoryError instance\n");
2260 goto finally;
2262 Py_DECREF(args);
2264 /* we're done with the exceptions module */
2265 Py_DECREF(m);
2267 if (PyErr_Occurred()) {
2268 PySys_WriteStderr("Cannot initialize standard class exceptions; ");
2269 if (Py_VerboseFlag) {
2270 PySys_WriteStderr("traceback:\n");
2271 PyErr_Print();
2273 else
2274 PySys_WriteStderr("use -v for traceback\n");
2275 goto finally;
2277 return 1;
2278 finally:
2279 Py_XDECREF(m);
2280 Py_XDECREF(args);
2281 PyErr_Clear();
2282 return 0;
2286 static void
2287 fini_instances()
2289 Py_XDECREF(PyExc_MemoryErrorInst);
2290 PyExc_MemoryErrorInst = NULL;
2294 static PyObject *
2295 newstdexception(dict, name)
2296 PyObject *dict;
2297 char *name;
2299 PyObject *v = PyString_FromString(name);
2300 if (v == NULL || PyDict_SetItemString(dict, name, v) != 0)
2301 Py_FatalError("Cannot create string-based exceptions");
2302 return v;
2305 static void
2306 initerrors(dict)
2307 PyObject *dict;
2309 int i, j;
2310 int exccnt = 0;
2311 for (i = 0; bltin_exc[i].name; i++, exccnt++) {
2312 Py_XDECREF(*bltin_exc[i].exc);
2313 if (bltin_exc[i].leaf_exc)
2314 *bltin_exc[i].exc =
2315 newstdexception(dict, bltin_exc[i].name);
2318 /* This is kind of bogus because we special case the some of the
2319 * new exceptions to be nearly forward compatible. But this means
2320 * we hard code knowledge about exceptions.py into C here. I don't
2321 * have a better solution, though.
2323 PyExc_LookupError = PyTuple_New(2);
2324 Py_INCREF(PyExc_IndexError);
2325 PyTuple_SET_ITEM(PyExc_LookupError, 0, PyExc_IndexError);
2326 Py_INCREF(PyExc_KeyError);
2327 PyTuple_SET_ITEM(PyExc_LookupError, 1, PyExc_KeyError);
2328 PyDict_SetItemString(dict, "LookupError", PyExc_LookupError);
2330 PyExc_ArithmeticError = PyTuple_New(3);
2331 Py_INCREF(PyExc_OverflowError);
2332 PyTuple_SET_ITEM(PyExc_ArithmeticError, 0, PyExc_OverflowError);
2333 Py_INCREF(PyExc_ZeroDivisionError);
2334 PyTuple_SET_ITEM(PyExc_ArithmeticError, 1, PyExc_ZeroDivisionError);
2335 Py_INCREF(PyExc_FloatingPointError);
2336 PyTuple_SET_ITEM(PyExc_ArithmeticError, 2, PyExc_FloatingPointError);
2337 PyDict_SetItemString(dict, "ArithmeticError", PyExc_ArithmeticError);
2339 PyExc_EnvironmentError = PyTuple_New(2);
2340 Py_INCREF(PyExc_IOError);
2341 PyTuple_SET_ITEM(PyExc_EnvironmentError, 0, PyExc_IOError);
2342 Py_INCREF(PyExc_OSError);
2343 PyTuple_SET_ITEM(PyExc_EnvironmentError, 1, PyExc_OSError);
2344 PyDict_SetItemString(dict, "EnvironmentError", PyExc_EnvironmentError);
2346 /* missing from the StandardError tuple: Exception, StandardError,
2347 * and SystemExit
2349 PyExc_StandardError = PyTuple_New(exccnt-3);
2350 for (i = 2, j = 0; bltin_exc[i].name; i++) {
2351 PyObject *exc = *bltin_exc[i].exc;
2352 /* SystemExit is not an error, but it is an exception */
2353 if (exc != PyExc_SystemExit) {
2354 Py_INCREF(exc);
2355 PyTuple_SET_ITEM(PyExc_StandardError, j++, exc);
2358 PyDict_SetItemString(dict, "StandardError", PyExc_StandardError);
2360 /* Exception is a 2-tuple */
2361 PyExc_Exception = PyTuple_New(2);
2362 Py_INCREF(PyExc_SystemExit);
2363 PyTuple_SET_ITEM(PyExc_Exception, 0, PyExc_SystemExit);
2364 Py_INCREF(PyExc_StandardError);
2365 PyTuple_SET_ITEM(PyExc_Exception, 1, PyExc_StandardError);
2366 PyDict_SetItemString(dict, "Exception", PyExc_Exception);
2368 if (PyErr_Occurred())
2369 Py_FatalError("Could not initialize built-in string exceptions");
2373 static void
2374 finierrors()
2376 int i;
2377 for (i = 0; bltin_exc[i].name; i++) {
2378 PyObject *exc = *bltin_exc[i].exc;
2379 Py_XDECREF(exc);
2380 *bltin_exc[i].exc = NULL;
2384 static char builtin_doc[] =
2385 "Built-in functions, exceptions, and other objects.\n\
2387 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.";
2389 PyObject *
2390 _PyBuiltin_Init_1()
2392 PyObject *mod, *dict;
2393 mod = Py_InitModule4("__builtin__", builtin_methods,
2394 builtin_doc, (PyObject *)NULL,
2395 PYTHON_API_VERSION);
2396 if (mod == NULL)
2397 return NULL;
2398 dict = PyModule_GetDict(mod);
2399 initerrors(dict);
2400 if (PyDict_SetItemString(dict, "None", Py_None) < 0)
2401 return NULL;
2402 if (PyDict_SetItemString(dict, "Ellipsis", Py_Ellipsis) < 0)
2403 return NULL;
2404 if (PyDict_SetItemString(dict, "__debug__",
2405 PyInt_FromLong(Py_OptimizeFlag == 0)) < 0)
2406 return NULL;
2408 return mod;
2411 void
2412 _PyBuiltin_Init_2(dict)
2413 PyObject *dict;
2415 /* if Python was started with -X, initialize the class exceptions */
2416 if (Py_UseClassExceptionsFlag) {
2417 if (!init_class_exc(dict)) {
2418 /* class based exceptions could not be
2419 * initialized. Fall back to using string based
2420 * exceptions.
2422 PySys_WriteStderr(
2423 "Warning! Falling back to string-based exceptions\n");
2424 initerrors(dict);
2430 void
2431 _PyBuiltin_Fini_1()
2433 fini_instances();
2437 void
2438 _PyBuiltin_Fini_2()
2440 finierrors();
2444 /* Helper for filter(): filter a tuple through a function */
2446 static PyObject *
2447 filtertuple(func, tuple)
2448 PyObject *func;
2449 PyObject *tuple;
2451 PyObject *result;
2452 register int i, j;
2453 int len = PyTuple_Size(tuple);
2455 if (len == 0) {
2456 Py_INCREF(tuple);
2457 return tuple;
2460 if ((result = PyTuple_New(len)) == NULL)
2461 return NULL;
2463 for (i = j = 0; i < len; ++i) {
2464 PyObject *item, *good;
2465 int ok;
2467 if ((item = PyTuple_GetItem(tuple, i)) == NULL)
2468 goto Fail_1;
2469 if (func == Py_None) {
2470 Py_INCREF(item);
2471 good = item;
2473 else {
2474 PyObject *arg = Py_BuildValue("(O)", item);
2475 if (arg == NULL)
2476 goto Fail_1;
2477 good = PyEval_CallObject(func, arg);
2478 Py_DECREF(arg);
2479 if (good == NULL)
2480 goto Fail_1;
2482 ok = PyObject_IsTrue(good);
2483 Py_DECREF(good);
2484 if (ok) {
2485 Py_INCREF(item);
2486 if (PyTuple_SetItem(result, j++, item) < 0)
2487 goto Fail_1;
2491 if (_PyTuple_Resize(&result, j, 0) < 0)
2492 return NULL;
2494 return result;
2496 Fail_1:
2497 Py_DECREF(result);
2498 return NULL;
2502 /* Helper for filter(): filter a string through a function */
2504 static PyObject *
2505 filterstring(func, strobj)
2506 PyObject *func;
2507 PyObject *strobj;
2509 PyObject *result;
2510 register int i, j;
2511 int len = PyString_Size(strobj);
2513 if (func == Py_None) {
2514 /* No character is ever false -- share input string */
2515 Py_INCREF(strobj);
2516 return strobj;
2518 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2519 return NULL;
2521 for (i = j = 0; i < len; ++i) {
2522 PyObject *item, *arg, *good;
2523 int ok;
2525 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2526 if (item == NULL)
2527 goto Fail_1;
2528 arg = Py_BuildValue("(O)", item);
2529 Py_DECREF(item);
2530 if (arg == NULL)
2531 goto Fail_1;
2532 good = PyEval_CallObject(func, arg);
2533 Py_DECREF(arg);
2534 if (good == NULL)
2535 goto Fail_1;
2536 ok = PyObject_IsTrue(good);
2537 Py_DECREF(good);
2538 if (ok)
2539 PyString_AS_STRING((PyStringObject *)result)[j++] =
2540 PyString_AS_STRING((PyStringObject *)item)[0];
2543 if (j < len && _PyString_Resize(&result, j) < 0)
2544 return NULL;
2546 return result;
2548 Fail_1:
2549 Py_DECREF(result);
2550 return NULL;