bltinmodule.c revision 4be47c0f76c349ee9c04b08ed122c8bd8190d2c5
1/***********************************************************
2Copyright (c) 2000, BeOpen.com.
3Copyright (c) 1995-2000, Corporation for National Research Initiatives.
4Copyright (c) 1990-1995, Stichting Mathematisch Centrum.
5All rights reserved.
6
7See the file "Misc/COPYRIGHT" for information on usage and
8redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
9******************************************************************/
10
11/* Built-in functions */
12
13#include "Python.h"
14
15#include "node.h"
16#include "compile.h"
17#include "eval.h"
18
19#include "mymath.h"
20
21#include <ctype.h>
22
23#ifdef HAVE_UNISTD_H
24#include <unistd.h>
25#endif
26#ifdef HAVE_LIMITS_H
27#include <limits.h>
28#endif
29
30/* Forward */
31static PyObject *filterstring Py_PROTO((PyObject *, PyObject *));
32static PyObject *filtertuple  Py_PROTO((PyObject *, PyObject *));
33
34static PyObject *
35builtin___import__(self, args)
36	PyObject *self;
37	PyObject *args;
38{
39	char *name;
40	PyObject *globals = NULL;
41	PyObject *locals = NULL;
42	PyObject *fromlist = NULL;
43
44	if (!PyArg_ParseTuple(args, "s|OOO:__import__",
45			&name, &globals, &locals, &fromlist))
46		return NULL;
47	return PyImport_ImportModuleEx(name, globals, locals, fromlist);
48}
49
50static char import_doc[] =
51"__import__(name, globals, locals, fromlist) -> module\n\
52\n\
53Import a module.  The globals are only used to determine the context;\n\
54they are not modified.  The locals are currently unused.  The fromlist\n\
55should be a list of names to emulate ``from name import ...'', or an\n\
56empty list to emulate ``import name''.\n\
57When importing a module from a package, note that __import__('A.B', ...)\n\
58returns package A when fromlist is empty, but its submodule B when\n\
59fromlist is not empty.";
60
61
62static PyObject *
63builtin_abs(self, args)
64	PyObject *self;
65	PyObject *args;
66{
67	PyObject *v;
68
69	if (!PyArg_ParseTuple(args, "O:abs", &v))
70		return NULL;
71	return PyNumber_Absolute(v);
72}
73
74static char abs_doc[] =
75"abs(number) -> number\n\
76\n\
77Return the absolute value of the argument.";
78
79
80static PyObject *
81builtin_apply(self, args)
82	PyObject *self;
83	PyObject *args;
84{
85	PyObject *func, *alist = NULL, *kwdict = NULL;
86	PyObject *t = NULL, *retval = NULL;
87
88	if (!PyArg_ParseTuple(args, "O|OO:apply", &func, &alist, &kwdict))
89		return NULL;
90	if (alist != NULL) {
91		if (!PyTuple_Check(alist)) {
92			if (!PySequence_Check(alist)) {
93				PyErr_SetString(PyExc_TypeError,
94				    "apply() 2nd argument must be a sequence");
95				return NULL;
96			}
97			t = PySequence_Tuple(alist);
98			if (t == NULL)
99				return NULL;
100			alist = t;
101		}
102	}
103	if (kwdict != NULL && !PyDict_Check(kwdict)) {
104		PyErr_SetString(PyExc_TypeError,
105			   "apply() 3rd argument must be dictionary");
106		goto finally;
107	}
108	retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
109  finally:
110	Py_XDECREF(t);
111	return retval;
112}
113
114static char apply_doc[] =
115"apply(object, args[, kwargs]) -> value\n\
116\n\
117Call a callable object with positional arguments taken from the tuple args,\n\
118and keyword arguments taken from the optional dictionary kwargs.\n\
119Note that classes are callable, as are instances with a __call__() method.";
120
121
122static PyObject *
123builtin_buffer(self, args)
124	PyObject *self;
125	PyObject *args;
126{
127	PyObject *ob;
128	int offset = 0;
129	int size = Py_END_OF_BUFFER;
130
131	if ( !PyArg_ParseTuple(args, "O|ii:buffer", &ob, &offset, &size) )
132	    return NULL;
133	return PyBuffer_FromObject(ob, offset, size);
134}
135
136static char buffer_doc[] =
137"buffer(object [, offset[, size]]) -> object\n\
138\n\
139Creates a new buffer object which references the given object.\n\
140The buffer will reference a slice of the target object from the\n\
141start of the object (or at the specified offset). The slice will\n\
142extend to the end of the target object (or with the specified size).";
143
144
145static PyObject *
146builtin_unicode(self, args)
147	PyObject *self;
148	PyObject *args;
149{
150        PyObject *v;
151	char *encoding = NULL;
152	char *errors = NULL;
153
154	if ( !PyArg_ParseTuple(args, "O|ss:unicode", &v, &encoding, &errors) )
155	    return NULL;
156	return PyUnicode_FromEncodedObject(v, encoding, errors);
157}
158
159static char unicode_doc[] =
160"unicode(string [, encoding[, errors]]) -> object\n\
161\n\
162Creates a new Unicode object from the given encoded string.\n\
163encoding defaults to the current default string encoding and \n\
164errors, defining the error handling, to 'strict'.";
165
166
167static PyObject *
168builtin_callable(self, args)
169	PyObject *self;
170	PyObject *args;
171{
172	PyObject *v;
173
174	if (!PyArg_ParseTuple(args, "O:callable", &v))
175		return NULL;
176	return PyInt_FromLong((long)PyCallable_Check(v));
177}
178
179static char callable_doc[] =
180"callable(object) -> Boolean\n\
181\n\
182Return whether the object is callable (i.e., some kind of function).\n\
183Note that classes are callable, as are instances with a __call__() method.";
184
185
186static PyObject *
187builtin_filter(self, args)
188	PyObject *self;
189	PyObject *args;
190{
191	PyObject *func, *seq, *result;
192	PySequenceMethods *sqf;
193	int len;
194	register int i, j;
195
196	if (!PyArg_ParseTuple(args, "OO:filter", &func, &seq))
197		return NULL;
198
199	if (PyString_Check(seq)) {
200		PyObject *r = filterstring(func, seq);
201		return r;
202	}
203
204	if (PyTuple_Check(seq)) {
205		PyObject *r = filtertuple(func, seq);
206		return r;
207	}
208
209	sqf = seq->ob_type->tp_as_sequence;
210	if (sqf == NULL || sqf->sq_length == NULL || sqf->sq_item == NULL) {
211		PyErr_SetString(PyExc_TypeError,
212			   "argument 2 to filter() must be a sequence type");
213		goto Fail_2;
214	}
215
216	if ((len = (*sqf->sq_length)(seq)) < 0)
217		goto Fail_2;
218
219	if (PyList_Check(seq) && seq->ob_refcnt == 1) {
220		Py_INCREF(seq);
221		result = seq;
222	}
223	else {
224		if ((result = PyList_New(len)) == NULL)
225			goto Fail_2;
226	}
227
228	for (i = j = 0; ; ++i) {
229		PyObject *item, *good;
230		int ok;
231
232		if ((item = (*sqf->sq_item)(seq, i)) == NULL) {
233			if (PyErr_ExceptionMatches(PyExc_IndexError)) {
234				PyErr_Clear();
235				break;
236			}
237			goto Fail_1;
238		}
239
240		if (func == Py_None) {
241			good = item;
242			Py_INCREF(good);
243		}
244		else {
245			PyObject *arg = Py_BuildValue("(O)", item);
246			if (arg == NULL)
247				goto Fail_1;
248			good = PyEval_CallObject(func, arg);
249			Py_DECREF(arg);
250			if (good == NULL) {
251				Py_DECREF(item);
252				goto Fail_1;
253			}
254		}
255		ok = PyObject_IsTrue(good);
256		Py_DECREF(good);
257		if (ok) {
258			if (j < len) {
259				if (PyList_SetItem(result, j++, item) < 0)
260					goto Fail_1;
261			}
262			else {
263				int status = PyList_Append(result, item);
264				j++;
265				Py_DECREF(item);
266				if (status < 0)
267					goto Fail_1;
268			}
269		} else {
270			Py_DECREF(item);
271		}
272	}
273
274
275	if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
276		goto Fail_1;
277
278	return result;
279
280Fail_1:
281	Py_DECREF(result);
282Fail_2:
283	return NULL;
284}
285
286static char filter_doc[] =
287"filter(function, sequence) -> list\n\
288\n\
289Return a list containing those items of sequence for which function(item)\n\
290is true.  If function is None, return a list of items that are true.";
291
292
293static PyObject *
294builtin_chr(self, args)
295	PyObject *self;
296	PyObject *args;
297{
298	long x;
299	char s[1];
300
301	if (!PyArg_ParseTuple(args, "l:chr", &x))
302		return NULL;
303	if (x < 0 || x >= 256) {
304		PyErr_SetString(PyExc_ValueError,
305				"chr() arg not in range(256)");
306		return NULL;
307	}
308	s[0] = (char)x;
309	return PyString_FromStringAndSize(s, 1);
310}
311
312static char chr_doc[] =
313"chr(i) -> character\n\
314\n\
315Return a string of one character with ordinal i; 0 <= i < 256.";
316
317
318static PyObject *
319builtin_unichr(self, args)
320	PyObject *self;
321	PyObject *args;
322{
323	long x;
324	Py_UNICODE s[1];
325
326	if (!PyArg_ParseTuple(args, "l:unichr", &x))
327		return NULL;
328	if (x < 0 || x >= 65536) {
329		PyErr_SetString(PyExc_ValueError,
330				"unichr() arg not in range(65536)");
331		return NULL;
332	}
333	s[0] = (Py_UNICODE)x;
334	return PyUnicode_FromUnicode(s, 1);
335}
336
337static char unichr_doc[] =
338"unichr(i) -> Unicode character\n\
339\n\
340Return a Unicode string of one character with ordinal i; 0 <= i < 65536.";
341
342
343static PyObject *
344builtin_cmp(self, args)
345	PyObject *self;
346	PyObject *args;
347{
348	PyObject *a, *b;
349	int c;
350
351	if (!PyArg_ParseTuple(args, "OO:cmp", &a, &b))
352		return NULL;
353	if (PyObject_Cmp(a, b, &c) < 0)
354		return NULL;
355	return PyInt_FromLong((long)c);
356}
357
358static char cmp_doc[] =
359"cmp(x, y) -> integer\n\
360\n\
361Return negative if x<y, zero if x==y, positive if x>y.";
362
363
364static PyObject *
365builtin_coerce(self, args)
366	PyObject *self;
367	PyObject *args;
368{
369	PyObject *v, *w;
370	PyObject *res;
371
372	if (!PyArg_ParseTuple(args, "OO:coerce", &v, &w))
373		return NULL;
374	if (PyNumber_Coerce(&v, &w) < 0)
375		return NULL;
376	res = Py_BuildValue("(OO)", v, w);
377	Py_DECREF(v);
378	Py_DECREF(w);
379	return res;
380}
381
382static char coerce_doc[] =
383"coerce(x, y) -> None or (x1, y1)\n\
384\n\
385When x and y can be coerced to values of the same type, return a tuple\n\
386containing the coerced values.  When they can't be coerced, return None.";
387
388
389static PyObject *
390builtin_compile(self, args)
391	PyObject *self;
392	PyObject *args;
393{
394	char *str;
395	char *filename;
396	char *startstr;
397	int start;
398
399	if (!PyArg_ParseTuple(args, "sss:compile", &str, &filename, &startstr))
400		return NULL;
401	if (strcmp(startstr, "exec") == 0)
402		start = Py_file_input;
403	else if (strcmp(startstr, "eval") == 0)
404		start = Py_eval_input;
405	else if (strcmp(startstr, "single") == 0)
406		start = Py_single_input;
407	else {
408		PyErr_SetString(PyExc_ValueError,
409		   "compile() mode must be 'exec' or 'eval' or 'single'");
410		return NULL;
411	}
412	return Py_CompileString(str, filename, start);
413}
414
415static char compile_doc[] =
416"compile(source, filename, mode) -> code object\n\
417\n\
418Compile the source string (a Python module, statement or expression)\n\
419into a code object that can be executed by the exec statement or eval().\n\
420The filename will be used for run-time error messages.\n\
421The mode must be 'exec' to compile a module, 'single' to compile a\n\
422single (interactive) statement, or 'eval' to compile an expression.";
423
424
425#ifndef WITHOUT_COMPLEX
426
427static PyObject *
428complex_from_string(v)
429	PyObject *v;
430{
431	extern double strtod Py_PROTO((const char *, char **));
432	const char *s, *start;
433	char *end;
434	double x=0.0, y=0.0, z;
435	int got_re=0, got_im=0, done=0;
436	int digit_or_dot;
437	int sw_error=0;
438	int sign;
439	char buffer[256]; /* For errors */
440	int len;
441
442	if (PyString_Check(v)) {
443		s = PyString_AS_STRING(v);
444		len = PyString_GET_SIZE(v);
445	}
446	else if (PyUnicode_Check(v)) {
447		char s_buffer[256];
448
449		if (PyUnicode_GET_SIZE(v) >= sizeof(s_buffer)) {
450			PyErr_SetString(PyExc_ValueError,
451				 "complex() literal too large to convert");
452			return NULL;
453		}
454		if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
455					    PyUnicode_GET_SIZE(v),
456					    s_buffer,
457					    NULL))
458			return NULL;
459		s = s_buffer;
460		len = strlen(s);
461	}
462	else if (PyObject_AsCharBuffer(v, &s, &len)) {
463		PyErr_SetString(PyExc_TypeError,
464				"complex() needs a string first argument");
465		return NULL;
466	}
467
468	/* position on first nonblank */
469	start = s;
470	while (*s && isspace(Py_CHARMASK(*s)))
471		s++;
472	if (s[0] == '\0') {
473		PyErr_SetString(PyExc_ValueError,
474				"empty string for complex()");
475		return NULL;
476	}
477
478	z = -1.0;
479	sign = 1;
480	do {
481
482		switch (*s) {
483
484		case '\0':
485			if (s-start != len) {
486				PyErr_SetString(
487					PyExc_ValueError,
488					"null byte in argument for complex()");
489				return NULL;
490			}
491			if(!done) sw_error=1;
492			break;
493
494		case '-':
495			sign = -1;
496				/* Fallthrough */
497		case '+':
498			if (done)  sw_error=1;
499			s++;
500			if  (  *s=='\0'||*s=='+'||*s=='-'  ||
501			       isspace(Py_CHARMASK(*s))  )  sw_error=1;
502			break;
503
504		case 'J':
505		case 'j':
506			if (got_im || done) {
507				sw_error = 1;
508				break;
509			}
510			if  (z<0.0) {
511				y=sign;
512			}
513			else{
514				y=sign*z;
515			}
516			got_im=1;
517			s++;
518			if  (*s!='+' && *s!='-' )
519				done=1;
520			break;
521
522		default:
523			if (isspace(Py_CHARMASK(*s))) {
524				while (*s && isspace(Py_CHARMASK(*s)))
525					s++;
526				if (s[0] != '\0')
527					sw_error=1;
528				else
529					done = 1;
530				break;
531			}
532			digit_or_dot =
533				(*s=='.' || isdigit(Py_CHARMASK(*s)));
534			if  (done||!digit_or_dot) {
535				sw_error=1;
536				break;
537			}
538			errno = 0;
539			PyFPE_START_PROTECT("strtod", return 0)
540				z = strtod(s, &end) ;
541			PyFPE_END_PROTECT(z)
542				if (errno != 0) {
543					sprintf(buffer,
544					  "float() out of range: %.150s", s);
545					PyErr_SetString(
546						PyExc_ValueError,
547						buffer);
548					return NULL;
549				}
550			s=end;
551			if  (*s=='J' || *s=='j') {
552
553				break;
554			}
555			if  (got_re) {
556				sw_error=1;
557				break;
558			}
559
560				/* accept a real part */
561			x=sign*z;
562			got_re=1;
563			if  (got_im)  done=1;
564			z = -1.0;
565			sign = 1;
566			break;
567
568		}  /* end of switch  */
569
570	} while (*s!='\0' && !sw_error);
571
572	if (sw_error) {
573		PyErr_SetString(PyExc_ValueError,
574				"malformed string for complex()");
575		return NULL;
576	}
577
578	return PyComplex_FromDoubles(x,y);
579}
580
581static PyObject *
582builtin_complex(self, args)
583	PyObject *self;
584	PyObject *args;
585{
586	PyObject *r, *i, *tmp;
587	PyNumberMethods *nbr, *nbi = NULL;
588	Py_complex cr, ci;
589	int own_r = 0;
590
591	i = NULL;
592	if (!PyArg_ParseTuple(args, "O|O:complex", &r, &i))
593		return NULL;
594	if (PyString_Check(r) || PyUnicode_Check(r))
595		return complex_from_string(r);
596	if ((nbr = r->ob_type->tp_as_number) == NULL ||
597	    nbr->nb_float == NULL ||
598	    (i != NULL &&
599	     ((nbi = i->ob_type->tp_as_number) == NULL ||
600	      nbi->nb_float == NULL))) {
601		PyErr_SetString(PyExc_TypeError,
602			   "complex() argument can't be converted to complex");
603		return NULL;
604	}
605	/* XXX Hack to support classes with __complex__ method */
606	if (PyInstance_Check(r)) {
607		static PyObject *complexstr;
608		PyObject *f;
609		if (complexstr == NULL) {
610			complexstr = PyString_InternFromString("__complex__");
611			if (complexstr == NULL)
612				return NULL;
613		}
614		f = PyObject_GetAttr(r, complexstr);
615		if (f == NULL)
616			PyErr_Clear();
617		else {
618			PyObject *args = Py_BuildValue("()");
619			if (args == NULL)
620				return NULL;
621			r = PyEval_CallObject(f, args);
622			Py_DECREF(args);
623			Py_DECREF(f);
624			if (r == NULL)
625				return NULL;
626			own_r = 1;
627		}
628	}
629	if (PyComplex_Check(r)) {
630		cr = ((PyComplexObject*)r)->cval;
631		if (own_r) {
632			Py_DECREF(r);
633		}
634	}
635	else {
636		tmp = (*nbr->nb_float)(r);
637		if (own_r) {
638			Py_DECREF(r);
639		}
640		if (tmp == NULL)
641			return NULL;
642		cr.real = PyFloat_AsDouble(tmp);
643		Py_DECREF(tmp);
644		cr.imag = 0.0;
645	}
646	if (i == NULL) {
647		ci.real = 0.0;
648		ci.imag = 0.0;
649	}
650	else if (PyComplex_Check(i))
651		ci = ((PyComplexObject*)i)->cval;
652	else {
653		tmp = (*nbi->nb_float)(i);
654		if (tmp == NULL)
655			return NULL;
656		ci.real = PyFloat_AsDouble(tmp);
657		Py_DECREF(tmp);
658		ci.imag = 0.;
659	}
660	cr.real -= ci.imag;
661	cr.imag += ci.real;
662	return PyComplex_FromCComplex(cr);
663}
664
665static char complex_doc[] =
666"complex(real[, imag]) -> complex number\n\
667\n\
668Create a complex number from a real part and an optional imaginary part.\n\
669This is equivalent to (real + imag*1j) where imag defaults to 0.";
670
671
672#endif
673
674static PyObject *
675builtin_dir(self, args)
676	PyObject *self;
677	PyObject *args;
678{
679	static char *attrlist[] = {"__members__", "__methods__", NULL};
680	PyObject *v = NULL, *l = NULL, *m = NULL;
681	PyObject *d, *x;
682	int i;
683	char **s;
684
685	if (!PyArg_ParseTuple(args, "|O:dir", &v))
686		return NULL;
687	if (v == NULL) {
688		x = PyEval_GetLocals();
689		if (x == NULL)
690			goto error;
691		l = PyMapping_Keys(x);
692		if (l == NULL)
693			goto error;
694	}
695	else {
696		d = PyObject_GetAttrString(v, "__dict__");
697		if (d == NULL)
698			PyErr_Clear();
699		else {
700			l = PyMapping_Keys(d);
701			if (l == NULL)
702				PyErr_Clear();
703			Py_DECREF(d);
704		}
705		if (l == NULL) {
706			l = PyList_New(0);
707			if (l == NULL)
708				goto error;
709		}
710		for (s = attrlist; *s != NULL; s++) {
711			m = PyObject_GetAttrString(v, *s);
712			if (m == NULL) {
713				PyErr_Clear();
714				continue;
715			}
716			for (i = 0; ; i++) {
717				x = PySequence_GetItem(m, i);
718				if (x == NULL) {
719					PyErr_Clear();
720					break;
721				}
722				if (PyList_Append(l, x) != 0) {
723					Py_DECREF(x);
724					Py_DECREF(m);
725					goto error;
726				}
727				Py_DECREF(x);
728			}
729			Py_DECREF(m);
730		}
731	}
732	if (PyList_Sort(l) != 0)
733		goto error;
734	return l;
735  error:
736	Py_XDECREF(l);
737	return NULL;
738}
739
740static char dir_doc[] =
741"dir([object]) -> list of strings\n\
742\n\
743Return an alphabetized list of names comprising (some of) the attributes\n\
744of the given object.  Without an argument, the names in the current scope\n\
745are listed.  With an instance argument, only the instance attributes are\n\
746returned.  With a class argument, attributes of the base class are not\n\
747returned.  For other types or arguments, this may list members or methods.";
748
749
750static PyObject *
751builtin_divmod(self, args)
752	PyObject *self;
753	PyObject *args;
754{
755	PyObject *v, *w;
756
757	if (!PyArg_ParseTuple(args, "OO:divmod", &v, &w))
758		return NULL;
759	return PyNumber_Divmod(v, w);
760}
761
762static char divmod_doc[] =
763"divmod(x, y) -> (div, mod)\n\
764\n\
765Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.";
766
767
768static PyObject *
769builtin_eval(self, args)
770	PyObject *self;
771	PyObject *args;
772{
773	PyObject *cmd;
774	PyObject *globals = Py_None, *locals = Py_None;
775	char *str;
776
777	if (!PyArg_ParseTuple(args, "O|O!O!:eval",
778			&cmd,
779			&PyDict_Type, &globals,
780			&PyDict_Type, &locals))
781		return NULL;
782	if (globals == Py_None) {
783		globals = PyEval_GetGlobals();
784		if (locals == Py_None)
785			locals = PyEval_GetLocals();
786	}
787	else if (locals == Py_None)
788		locals = globals;
789	if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
790		if (PyDict_SetItemString(globals, "__builtins__",
791					 PyEval_GetBuiltins()) != 0)
792			return NULL;
793	}
794	if (PyCode_Check(cmd))
795		return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
796	if (!PyString_Check(cmd)) {
797		PyErr_SetString(PyExc_TypeError,
798			   "eval() argument 1 must be string or code object");
799		return NULL;
800	}
801	str = PyString_AsString(cmd);
802	if (strlen(str) != (size_t)PyString_Size(cmd)) {
803		PyErr_SetString(PyExc_ValueError,
804			   "embedded '\\0' in string arg");
805		return NULL;
806	}
807	while (*str == ' ' || *str == '\t')
808		str++;
809	return PyRun_String(str, Py_eval_input, globals, locals);
810}
811
812static char eval_doc[] =
813"eval(source[, globals[, locals]]) -> value\n\
814\n\
815Evaluate the source in the context of globals and locals.\n\
816The source may be a string representing a Python expression\n\
817or a code object as returned by compile().\n\
818The globals and locals are dictionaries, defaulting to the current\n\
819globals and locals.  If only globals is given, locals defaults to it.";
820
821
822static PyObject *
823builtin_execfile(self, args)
824	PyObject *self;
825	PyObject *args;
826{
827	char *filename;
828	PyObject *globals = Py_None, *locals = Py_None;
829	PyObject *res;
830	FILE* fp;
831
832	if (!PyArg_ParseTuple(args, "s|O!O!:execfile",
833			&filename,
834			&PyDict_Type, &globals,
835			&PyDict_Type, &locals))
836		return NULL;
837	if (globals == Py_None) {
838		globals = PyEval_GetGlobals();
839		if (locals == Py_None)
840			locals = PyEval_GetLocals();
841	}
842	else if (locals == Py_None)
843		locals = globals;
844	if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
845		if (PyDict_SetItemString(globals, "__builtins__",
846					 PyEval_GetBuiltins()) != 0)
847			return NULL;
848	}
849	Py_BEGIN_ALLOW_THREADS
850	fp = fopen(filename, "r");
851	Py_END_ALLOW_THREADS
852	if (fp == NULL) {
853		PyErr_SetFromErrno(PyExc_IOError);
854		return NULL;
855	}
856	res = PyRun_File(fp, filename, Py_file_input, globals, locals);
857	Py_BEGIN_ALLOW_THREADS
858	fclose(fp);
859	Py_END_ALLOW_THREADS
860	return res;
861}
862
863static char execfile_doc[] =
864"execfile(filename[, globals[, locals]])\n\
865\n\
866Read and execute a Python script from a file.\n\
867The globals and locals are dictionaries, defaulting to the current\n\
868globals and locals.  If only globals is given, locals defaults to it.";
869
870
871static PyObject *
872builtin_getattr(self, args)
873	PyObject *self;
874	PyObject *args;
875{
876	PyObject *v, *result, *dflt = NULL;
877	PyObject *name;
878
879	if (!PyArg_ParseTuple(args, "OS|O:getattr", &v, &name, &dflt))
880		return NULL;
881	result = PyObject_GetAttr(v, name);
882	if (result == NULL && dflt != NULL) {
883		PyErr_Clear();
884		Py_INCREF(dflt);
885		result = dflt;
886	}
887	return result;
888}
889
890static char getattr_doc[] =
891"getattr(object, name[, default]) -> value\n\
892\n\
893Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
894When a default argument is given, it is returned when the attribute doesn't\n\
895exist; without it, an exception is raised in that case.";
896
897
898static PyObject *
899builtin_globals(self, args)
900	PyObject *self;
901	PyObject *args;
902{
903	PyObject *d;
904
905	if (!PyArg_ParseTuple(args, ":globals"))
906		return NULL;
907	d = PyEval_GetGlobals();
908	Py_INCREF(d);
909	return d;
910}
911
912static char globals_doc[] =
913"globals() -> dictionary\n\
914\n\
915Return the dictionary containing the current scope's global variables.";
916
917
918static PyObject *
919builtin_hasattr(self, args)
920	PyObject *self;
921	PyObject *args;
922{
923	PyObject *v;
924	PyObject *name;
925
926	if (!PyArg_ParseTuple(args, "OS:hasattr", &v, &name))
927		return NULL;
928	v = PyObject_GetAttr(v, name);
929	if (v == NULL) {
930		PyErr_Clear();
931		Py_INCREF(Py_False);
932		return Py_False;
933	}
934	Py_DECREF(v);
935	Py_INCREF(Py_True);
936	return Py_True;
937}
938
939static char hasattr_doc[] =
940"hasattr(object, name) -> Boolean\n\
941\n\
942Return whether the object has an attribute with the given name.\n\
943(This is done by calling getattr(object, name) and catching exceptions.)";
944
945
946static PyObject *
947builtin_id(self, args)
948	PyObject *self;
949	PyObject *args;
950{
951	PyObject *v;
952
953	if (!PyArg_ParseTuple(args, "O:id", &v))
954		return NULL;
955	return PyLong_FromVoidPtr(v);
956}
957
958static char id_doc[] =
959"id(object) -> integer\n\
960\n\
961Return the identity of an object.  This is guaranteed to be unique among\n\
962simultaneously existing objects.  (Hint: it's the object's memory address.)";
963
964
965static PyObject *
966builtin_map(self, args)
967	PyObject *self;
968	PyObject *args;
969{
970	typedef struct {
971		PyObject *seq;
972		PySequenceMethods *sqf;
973		int len;
974	} sequence;
975
976	PyObject *func, *result;
977	sequence *seqs = NULL, *sqp;
978	int n, len;
979	register int i, j;
980
981	n = PyTuple_Size(args);
982	if (n < 2) {
983		PyErr_SetString(PyExc_TypeError,
984				"map() requires at least two args");
985		return NULL;
986	}
987
988	func = PyTuple_GetItem(args, 0);
989	n--;
990
991	if (func == Py_None && n == 1) {
992		/* map(None, S) is the same as list(S). */
993		return PySequence_List(PyTuple_GetItem(args, 1));
994	}
995
996	if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
997		PyErr_NoMemory();
998		goto Fail_2;
999	}
1000
1001	for (len = 0, i = 0, sqp = seqs; i < n; ++i, ++sqp) {
1002		int curlen;
1003		PySequenceMethods *sqf;
1004
1005		if ((sqp->seq = PyTuple_GetItem(args, i + 1)) == NULL)
1006			goto Fail_2;
1007
1008		sqp->sqf = sqf = sqp->seq->ob_type->tp_as_sequence;
1009		if (sqf == NULL ||
1010		    sqf->sq_length == NULL ||
1011		    sqf->sq_item == NULL)
1012		{
1013			static char errmsg[] =
1014			    "argument %d to map() must be a sequence object";
1015			char errbuf[sizeof(errmsg) + 25];
1016
1017			sprintf(errbuf, errmsg, i+2);
1018			PyErr_SetString(PyExc_TypeError, errbuf);
1019			goto Fail_2;
1020		}
1021
1022		if ((curlen = sqp->len = (*sqp->sqf->sq_length)(sqp->seq)) < 0)
1023			goto Fail_2;
1024
1025		if (curlen > len)
1026			len = curlen;
1027	}
1028
1029	if ((result = (PyObject *) PyList_New(len)) == NULL)
1030		goto Fail_2;
1031
1032	for (i = 0; ; ++i) {
1033		PyObject *alist, *item=NULL, *value;
1034		int any = 0;
1035
1036		if (func == Py_None && n == 1)
1037			alist = NULL;
1038		else {
1039			if ((alist = PyTuple_New(n)) == NULL)
1040				goto Fail_1;
1041		}
1042
1043		for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
1044			if (sqp->len < 0) {
1045				Py_INCREF(Py_None);
1046				item = Py_None;
1047			}
1048			else {
1049				item = (*sqp->sqf->sq_item)(sqp->seq, i);
1050				if (item == NULL) {
1051					if (PyErr_ExceptionMatches(
1052						PyExc_IndexError))
1053					{
1054						PyErr_Clear();
1055						Py_INCREF(Py_None);
1056						item = Py_None;
1057						sqp->len = -1;
1058					}
1059					else {
1060						goto Fail_0;
1061					}
1062				}
1063				else
1064					any = 1;
1065
1066			}
1067			if (!alist)
1068				break;
1069			if (PyTuple_SetItem(alist, j, item) < 0) {
1070				Py_DECREF(item);
1071				goto Fail_0;
1072			}
1073			continue;
1074
1075		Fail_0:
1076			Py_XDECREF(alist);
1077			goto Fail_1;
1078		}
1079
1080		if (!alist)
1081			alist = item;
1082
1083		if (!any) {
1084			Py_DECREF(alist);
1085			break;
1086		}
1087
1088		if (func == Py_None)
1089			value = alist;
1090		else {
1091			value = PyEval_CallObject(func, alist);
1092			Py_DECREF(alist);
1093			if (value == NULL)
1094				goto Fail_1;
1095		}
1096		if (i >= len) {
1097			int status = PyList_Append(result, value);
1098			Py_DECREF(value);
1099			if (status < 0)
1100				goto Fail_1;
1101		}
1102		else {
1103			if (PyList_SetItem(result, i, value) < 0)
1104				goto Fail_1;
1105		}
1106	}
1107
1108	if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
1109		goto Fail_1;
1110
1111	PyMem_DEL(seqs);
1112	return result;
1113
1114Fail_1:
1115	Py_DECREF(result);
1116Fail_2:
1117	if (seqs) PyMem_DEL(seqs);
1118	return NULL;
1119}
1120
1121static char map_doc[] =
1122"map(function, sequence[, sequence, ...]) -> list\n\
1123\n\
1124Return a list of the results of applying the function to the items of\n\
1125the argument sequence(s).  If more than one sequence is given, the\n\
1126function is called with an argument list consisting of the corresponding\n\
1127item of each sequence, substituting None for missing values when not all\n\
1128sequences have the same length.  If the function is None, return a list of\n\
1129the items of the sequence (or a list of tuples if more than one sequence).";
1130
1131
1132static PyObject *
1133builtin_setattr(self, args)
1134	PyObject *self;
1135	PyObject *args;
1136{
1137	PyObject *v;
1138	PyObject *name;
1139	PyObject *value;
1140
1141	if (!PyArg_ParseTuple(args, "OSO:setattr", &v, &name, &value))
1142		return NULL;
1143	if (PyObject_SetAttr(v, name, value) != 0)
1144		return NULL;
1145	Py_INCREF(Py_None);
1146	return Py_None;
1147}
1148
1149static char setattr_doc[] =
1150"setattr(object, name, value)\n\
1151\n\
1152Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1153``x.y = v''.";
1154
1155
1156static PyObject *
1157builtin_delattr(self, args)
1158	PyObject *self;
1159	PyObject *args;
1160{
1161	PyObject *v;
1162	PyObject *name;
1163
1164	if (!PyArg_ParseTuple(args, "OS:delattr", &v, &name))
1165		return NULL;
1166	if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1167		return NULL;
1168	Py_INCREF(Py_None);
1169	return Py_None;
1170}
1171
1172static char delattr_doc[] =
1173"delattr(object, name)\n\
1174\n\
1175Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1176``del x.y''.";
1177
1178
1179static PyObject *
1180builtin_hash(self, args)
1181	PyObject *self;
1182	PyObject *args;
1183{
1184	PyObject *v;
1185	long x;
1186
1187	if (!PyArg_ParseTuple(args, "O:hash", &v))
1188		return NULL;
1189	x = PyObject_Hash(v);
1190	if (x == -1)
1191		return NULL;
1192	return PyInt_FromLong(x);
1193}
1194
1195static char hash_doc[] =
1196"hash(object) -> integer\n\
1197\n\
1198Return a hash value for the object.  Two objects with the same value have\n\
1199the same hash value.  The reverse is not necessarily true, but likely.";
1200
1201
1202static PyObject *
1203builtin_hex(self, args)
1204	PyObject *self;
1205	PyObject *args;
1206{
1207	PyObject *v;
1208	PyNumberMethods *nb;
1209
1210	if (!PyArg_ParseTuple(args, "O:hex", &v))
1211		return NULL;
1212
1213	if ((nb = v->ob_type->tp_as_number) == NULL ||
1214	    nb->nb_hex == NULL) {
1215		PyErr_SetString(PyExc_TypeError,
1216			   "hex() argument can't be converted to hex");
1217		return NULL;
1218	}
1219	return (*nb->nb_hex)(v);
1220}
1221
1222static char hex_doc[] =
1223"hex(number) -> string\n\
1224\n\
1225Return the hexadecimal representation of an integer or long integer.";
1226
1227
1228static PyObject *builtin_raw_input Py_PROTO((PyObject *, PyObject *));
1229
1230static PyObject *
1231builtin_input(self, args)
1232	PyObject *self;
1233	PyObject *args;
1234{
1235	PyObject *line;
1236	char *str;
1237	PyObject *res;
1238	PyObject *globals, *locals;
1239
1240	line = builtin_raw_input(self, args);
1241	if (line == NULL)
1242		return line;
1243	if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1244		return NULL;
1245	while (*str == ' ' || *str == '\t')
1246			str++;
1247	globals = PyEval_GetGlobals();
1248	locals = PyEval_GetLocals();
1249	if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1250		if (PyDict_SetItemString(globals, "__builtins__",
1251					 PyEval_GetBuiltins()) != 0)
1252			return NULL;
1253	}
1254	res = PyRun_String(str, Py_eval_input, globals, locals);
1255	Py_DECREF(line);
1256	return res;
1257}
1258
1259static char input_doc[] =
1260"input([prompt]) -> value\n\
1261\n\
1262Equivalent to eval(raw_input(prompt)).";
1263
1264
1265static PyObject *
1266builtin_intern(self, args)
1267	PyObject *self;
1268	PyObject *args;
1269{
1270	PyObject *s;
1271	if (!PyArg_ParseTuple(args, "S:intern", &s))
1272		return NULL;
1273	Py_INCREF(s);
1274	PyString_InternInPlace(&s);
1275	return s;
1276}
1277
1278static char intern_doc[] =
1279"intern(string) -> string\n\
1280\n\
1281``Intern'' the given string.  This enters the string in the (global)\n\
1282table of interned strings whose purpose is to speed up dictionary lookups.\n\
1283Return the string itself or the previously interned string object with the\n\
1284same value.";
1285
1286
1287static PyObject *
1288builtin_int(self, args)
1289	PyObject *self;
1290	PyObject *args;
1291{
1292	PyObject *v;
1293	int base = -909;		     /* unlikely! */
1294
1295	if (!PyArg_ParseTuple(args, "O|i:int", &v, &base))
1296		return NULL;
1297	if (base == -909)
1298		return PyNumber_Int(v);
1299	else if (PyString_Check(v))
1300		return PyInt_FromString(PyString_AS_STRING(v), NULL, base);
1301	else if (PyUnicode_Check(v))
1302		return PyInt_FromUnicode(PyUnicode_AS_UNICODE(v),
1303					 PyUnicode_GET_SIZE(v),
1304					 base);
1305	else {
1306		PyErr_SetString(PyExc_TypeError,
1307				"can't convert non-string with explicit base");
1308		return NULL;
1309	}
1310}
1311
1312static char int_doc[] =
1313"int(x[, base]) -> integer\n\
1314\n\
1315Convert a string or number to an integer, if possible.  A floating point\n\
1316argument will be truncated towards zero (this does not include a string\n\
1317representation of a floating point number!)  When converting a string, use\n\
1318the optional base.  It is an error to supply a base when converting a\n\
1319non-string.";
1320
1321
1322static PyObject *
1323builtin_long(self, args)
1324	PyObject *self;
1325	PyObject *args;
1326{
1327	PyObject *v;
1328	int base = -909;		     /* unlikely! */
1329
1330	if (!PyArg_ParseTuple(args, "O|i:long", &v, &base))
1331		return NULL;
1332	if (base == -909)
1333		return PyNumber_Long(v);
1334	else if (PyString_Check(v))
1335		return PyLong_FromString(PyString_AS_STRING(v), NULL, base);
1336	else if (PyUnicode_Check(v))
1337		return PyLong_FromUnicode(PyUnicode_AS_UNICODE(v),
1338					  PyUnicode_GET_SIZE(v),
1339					  base);
1340	else {
1341		PyErr_SetString(PyExc_TypeError,
1342				"can't convert non-string with explicit base");
1343		return NULL;
1344	}
1345}
1346
1347static char long_doc[] =
1348"long(x) -> long integer\n\
1349long(x, base) -> long integer\n\
1350\n\
1351Convert a string or number to a long integer, if possible.  A floating\n\
1352point argument will be truncated towards zero (this does not include a\n\
1353string representation of a floating point number!)  When converting a\n\
1354string, use the given base.  It is an error to supply a base when\n\
1355converting a non-string.";
1356
1357
1358static PyObject *
1359builtin_float(self, args)
1360	PyObject *self;
1361	PyObject *args;
1362{
1363	PyObject *v;
1364
1365	if (!PyArg_ParseTuple(args, "O:float", &v))
1366		return NULL;
1367	if (PyString_Check(v))
1368		return PyFloat_FromString(v, NULL);
1369	return PyNumber_Float(v);
1370}
1371
1372static char float_doc[] =
1373"float(x) -> floating point number\n\
1374\n\
1375Convert a string or number to a floating point number, if possible.";
1376
1377
1378static PyObject *
1379builtin_len(self, args)
1380	PyObject *self;
1381	PyObject *args;
1382{
1383	PyObject *v;
1384	long res;
1385
1386	if (!PyArg_ParseTuple(args, "O:len", &v))
1387		return NULL;
1388	res = PyObject_Length(v);
1389	if (res < 0 && PyErr_Occurred())
1390		return NULL;
1391	return PyInt_FromLong(res);
1392}
1393
1394static char len_doc[] =
1395"len(object) -> integer\n\
1396\n\
1397Return the number of items of a sequence or mapping.";
1398
1399
1400static PyObject *
1401builtin_list(self, args)
1402	PyObject *self;
1403	PyObject *args;
1404{
1405	PyObject *v;
1406
1407	if (!PyArg_ParseTuple(args, "O:list", &v))
1408		return NULL;
1409	return PySequence_List(v);
1410}
1411
1412static char list_doc[] =
1413"list(sequence) -> list\n\
1414\n\
1415Return a new list whose items are the same as those of the argument sequence.";
1416
1417
1418static PyObject *
1419builtin_slice(self, args)
1420     PyObject *self;
1421     PyObject *args;
1422{
1423	PyObject *start, *stop, *step;
1424
1425	start = stop = step = NULL;
1426
1427	if (!PyArg_ParseTuple(args, "O|OO:slice", &start, &stop, &step))
1428		return NULL;
1429
1430	/* This swapping of stop and start is to maintain similarity with
1431	   range(). */
1432	if (stop == NULL) {
1433		stop = start;
1434		start = NULL;
1435	}
1436	return PySlice_New(start, stop, step);
1437}
1438
1439static char slice_doc[] =
1440"slice([start,] stop[, step]) -> slice object\n\
1441\n\
1442Create a slice object.  This is used for slicing by the Numeric extensions.";
1443
1444
1445static PyObject *
1446builtin_locals(self, args)
1447	PyObject *self;
1448	PyObject *args;
1449{
1450	PyObject *d;
1451
1452	if (!PyArg_ParseTuple(args, ":locals"))
1453		return NULL;
1454	d = PyEval_GetLocals();
1455	Py_INCREF(d);
1456	return d;
1457}
1458
1459static char locals_doc[] =
1460"locals() -> dictionary\n\
1461\n\
1462Return the dictionary containing the current scope's local variables.";
1463
1464
1465static PyObject *
1466min_max(args, sign)
1467	PyObject *args;
1468	int sign;
1469{
1470	int i;
1471	PyObject *v, *w, *x;
1472	PySequenceMethods *sq;
1473
1474	if (PyTuple_Size(args) > 1)
1475		v = args;
1476	else if (!PyArg_ParseTuple(args, "O:min/max", &v))
1477		return NULL;
1478	sq = v->ob_type->tp_as_sequence;
1479	if (sq == NULL || sq->sq_item == NULL) {
1480		PyErr_SetString(PyExc_TypeError,
1481				"min() or max() of non-sequence");
1482		return NULL;
1483	}
1484	w = NULL;
1485	for (i = 0; ; i++) {
1486		x = (*sq->sq_item)(v, i); /* Implies INCREF */
1487		if (x == NULL) {
1488			if (PyErr_ExceptionMatches(PyExc_IndexError)) {
1489				PyErr_Clear();
1490				break;
1491			}
1492			Py_XDECREF(w);
1493			return NULL;
1494		}
1495		if (w == NULL)
1496			w = x;
1497		else {
1498			int c = PyObject_Compare(x, w);
1499			if (c && PyErr_Occurred()) {
1500				Py_DECREF(x);
1501				Py_XDECREF(w);
1502				return NULL;
1503			}
1504			if (c * sign > 0) {
1505				Py_DECREF(w);
1506				w = x;
1507			}
1508			else
1509				Py_DECREF(x);
1510		}
1511	}
1512	if (w == NULL)
1513		PyErr_SetString(PyExc_ValueError,
1514				"min() or max() of empty sequence");
1515	return w;
1516}
1517
1518static PyObject *
1519builtin_min(self, v)
1520	PyObject *self;
1521	PyObject *v;
1522{
1523	return min_max(v, -1);
1524}
1525
1526static char min_doc[] =
1527"min(sequence) -> value\n\
1528min(a, b, c, ...) -> value\n\
1529\n\
1530With a single sequence argument, return its smallest item.\n\
1531With two or more arguments, return the smallest argument.";
1532
1533
1534static PyObject *
1535builtin_max(self, v)
1536	PyObject *self;
1537	PyObject *v;
1538{
1539	return min_max(v, 1);
1540}
1541
1542static char max_doc[] =
1543"max(sequence) -> value\n\
1544max(a, b, c, ...) -> value\n\
1545\n\
1546With a single sequence argument, return its largest item.\n\
1547With two or more arguments, return the largest argument.";
1548
1549
1550static PyObject *
1551builtin_oct(self, args)
1552	PyObject *self;
1553	PyObject *args;
1554{
1555	PyObject *v;
1556	PyNumberMethods *nb;
1557
1558	if (!PyArg_ParseTuple(args, "O:oct", &v))
1559		return NULL;
1560	if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1561	    nb->nb_oct == NULL) {
1562		PyErr_SetString(PyExc_TypeError,
1563			   "oct() argument can't be converted to oct");
1564		return NULL;
1565	}
1566	return (*nb->nb_oct)(v);
1567}
1568
1569static char oct_doc[] =
1570"oct(number) -> string\n\
1571\n\
1572Return the octal representation of an integer or long integer.";
1573
1574
1575static PyObject *
1576builtin_open(self, args)
1577	PyObject *self;
1578	PyObject *args;
1579{
1580	char *name;
1581	char *mode = "r";
1582	int bufsize = -1;
1583	PyObject *f;
1584
1585	if (!PyArg_ParseTuple(args, "s|si:open", &name, &mode, &bufsize))
1586		return NULL;
1587	f = PyFile_FromString(name, mode);
1588	if (f != NULL)
1589		PyFile_SetBufSize(f, bufsize);
1590	return f;
1591}
1592
1593static char open_doc[] =
1594"open(filename[, mode[, buffering]]) -> file object\n\
1595\n\
1596Open a file.  The mode can be 'r', 'w' or 'a' for reading (default),\n\
1597writing or appending.  The file will be created if it doesn't exist\n\
1598when opened for writing or appending; it will be truncated when\n\
1599opened for writing.  Add a 'b' to the mode for binary files.\n\
1600Add a '+' to the mode to allow simultaneous reading and writing.\n\
1601If the buffering argument is given, 0 means unbuffered, 1 means line\n\
1602buffered, and larger numbers specify the buffer size.";
1603
1604
1605static PyObject *
1606builtin_ord(self, args)
1607	PyObject *self;
1608	PyObject *args;
1609{
1610	PyObject *obj;
1611	long ord;
1612	int size;
1613
1614	if (!PyArg_ParseTuple(args, "O:ord", &obj))
1615		return NULL;
1616
1617	if (PyString_Check(obj)) {
1618		size = PyString_GET_SIZE(obj);
1619		if (size == 1)
1620			ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1621	} else if (PyUnicode_Check(obj)) {
1622		size = PyUnicode_GET_SIZE(obj);
1623		if (size == 1)
1624			ord = (long)*PyUnicode_AS_UNICODE(obj);
1625	} else {
1626		PyErr_Format(PyExc_TypeError,
1627			     "expected string or Unicode character, " \
1628			     "%.200s found", obj->ob_type->tp_name);
1629		return NULL;
1630	}
1631	if (size == 1)
1632		return PyInt_FromLong(ord);
1633
1634	PyErr_Format(PyExc_TypeError,
1635		     "expected a character, length-%d string found",
1636		     size);
1637	return NULL;
1638}
1639
1640static char ord_doc[] =
1641"ord(c) -> integer\n\
1642\n\
1643Return the integer ordinal of a one character string.";
1644
1645
1646static PyObject *
1647builtin_pow(self, args)
1648	PyObject *self;
1649	PyObject *args;
1650{
1651	PyObject *v, *w, *z = Py_None;
1652
1653	if (!PyArg_ParseTuple(args, "OO|O:pow", &v, &w, &z))
1654		return NULL;
1655	return PyNumber_Power(v, w, z);
1656}
1657
1658static char pow_doc[] =
1659"pow(x, y[, z]) -> number\n\
1660\n\
1661With two arguments, equivalent to x**y.  With three arguments,\n\
1662equivalent to (x**y) % z, but may be more efficient (e.g. for longs).";
1663
1664
1665/* Return number of items in range/xrange (lo, hi, step).  step > 0
1666 * required.  Return a value < 0 if & only if the true value is too
1667 * large to fit in a signed long.
1668 */
1669static long
1670get_len_of_range(lo, hi, step)
1671	long lo;
1672	long hi;
1673	long step;	/* must be > 0 */
1674{
1675	/* -------------------------------------------------------------
1676	If lo >= hi, the range is empty.
1677	Else if n values are in the range, the last one is
1678	lo + (n-1)*step, which must be <= hi-1.  Rearranging,
1679	n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1680	the proper value.  Since lo < hi in this case, hi-lo-1 >= 0, so
1681	the RHS is non-negative and so truncation is the same as the
1682	floor.  Letting M be the largest positive long, the worst case
1683	for the RHS numerator is hi=M, lo=-M-1, and then
1684	hi-lo-1 = M-(-M-1)-1 = 2*M.  Therefore unsigned long has enough
1685	precision to compute the RHS exactly.
1686	---------------------------------------------------------------*/
1687	long n = 0;
1688	if (lo < hi) {
1689		unsigned long uhi = (unsigned long)hi;
1690		unsigned long ulo = (unsigned long)lo;
1691		unsigned long diff = uhi - ulo - 1;
1692		n = (long)(diff / (unsigned long)step + 1);
1693	}
1694	return n;
1695}
1696
1697static PyObject *
1698builtin_range(self, args)
1699	PyObject *self;
1700	PyObject *args;
1701{
1702	long ilow = 0, ihigh = 0, istep = 1;
1703	long bign;
1704	int i, n;
1705
1706	PyObject *v;
1707
1708	if (PyTuple_Size(args) <= 1) {
1709		if (!PyArg_ParseTuple(args,
1710				"l;range() requires 1-3 int arguments",
1711				&ihigh))
1712			return NULL;
1713	}
1714	else {
1715		if (!PyArg_ParseTuple(args,
1716				"ll|l;range() requires 1-3 int arguments",
1717				&ilow, &ihigh, &istep))
1718			return NULL;
1719	}
1720	if (istep == 0) {
1721		PyErr_SetString(PyExc_ValueError, "zero step for range()");
1722		return NULL;
1723	}
1724	if (istep > 0)
1725		bign = get_len_of_range(ilow, ihigh, istep);
1726	else
1727		bign = get_len_of_range(ihigh, ilow, -istep);
1728	n = (int)bign;
1729	if (bign < 0 || (long)n != bign) {
1730		PyErr_SetString(PyExc_OverflowError,
1731				"range() has too many items");
1732		return NULL;
1733	}
1734	v = PyList_New(n);
1735	if (v == NULL)
1736		return NULL;
1737	for (i = 0; i < n; i++) {
1738		PyObject *w = PyInt_FromLong(ilow);
1739		if (w == NULL) {
1740			Py_DECREF(v);
1741			return NULL;
1742		}
1743		PyList_SET_ITEM(v, i, w);
1744		ilow += istep;
1745	}
1746	return v;
1747}
1748
1749static char range_doc[] =
1750"range([start,] stop[, step]) -> list of integers\n\
1751\n\
1752Return a list containing an arithmetic progression of integers.\n\
1753range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1754When step is given, it specifies the increment (or decrement).\n\
1755For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!\n\
1756These are exactly the valid indices for a list of 4 elements.";
1757
1758
1759static PyObject *
1760builtin_xrange(self, args)
1761	PyObject *self;
1762	PyObject *args;
1763{
1764	long ilow = 0, ihigh = 0, istep = 1;
1765	long n;
1766
1767	if (PyTuple_Size(args) <= 1) {
1768		if (!PyArg_ParseTuple(args,
1769				"l;xrange() requires 1-3 int arguments",
1770				&ihigh))
1771			return NULL;
1772	}
1773	else {
1774		if (!PyArg_ParseTuple(args,
1775				"ll|l;xrange() requires 1-3 int arguments",
1776				&ilow, &ihigh, &istep))
1777			return NULL;
1778	}
1779	if (istep == 0) {
1780		PyErr_SetString(PyExc_ValueError, "zero step for xrange()");
1781		return NULL;
1782	}
1783	if (istep > 0)
1784		n = get_len_of_range(ilow, ihigh, istep);
1785	else
1786		n = get_len_of_range(ihigh, ilow, -istep);
1787	if (n < 0) {
1788		PyErr_SetString(PyExc_OverflowError,
1789				"xrange() has more than sys.maxint items");
1790		return NULL;
1791	}
1792	return PyRange_New(ilow, n, istep, 1);
1793}
1794
1795static char xrange_doc[] =
1796"xrange([start,] stop[, step]) -> xrange object\n\
1797\n\
1798Like range(), but instead of returning a list, returns an object that\n\
1799generates the numbers in the range on demand.  This is slightly slower\n\
1800than range() but more memory efficient.";
1801
1802
1803static PyObject *
1804builtin_raw_input(self, args)
1805	PyObject *self;
1806	PyObject *args;
1807{
1808	PyObject *v = NULL;
1809	PyObject *f;
1810
1811	if (!PyArg_ParseTuple(args, "|O:[raw_]input", &v))
1812		return NULL;
1813	if (PyFile_AsFile(PySys_GetObject("stdin")) == stdin &&
1814	    PyFile_AsFile(PySys_GetObject("stdout")) == stdout &&
1815	    isatty(fileno(stdin)) && isatty(fileno(stdout))) {
1816		PyObject *po;
1817		char *prompt;
1818		char *s;
1819		PyObject *result;
1820		if (v != NULL) {
1821			po = PyObject_Str(v);
1822			if (po == NULL)
1823				return NULL;
1824			prompt = PyString_AsString(po);
1825			if (prompt == NULL)
1826				return NULL;
1827		}
1828		else {
1829			po = NULL;
1830			prompt = "";
1831		}
1832		s = PyOS_Readline(prompt);
1833		Py_XDECREF(po);
1834		if (s == NULL) {
1835			PyErr_SetNone(PyExc_KeyboardInterrupt);
1836			return NULL;
1837		}
1838		if (*s == '\0') {
1839			PyErr_SetNone(PyExc_EOFError);
1840			result = NULL;
1841		}
1842		else { /* strip trailing '\n' */
1843			size_t len = strlen(s);
1844			if (len > INT_MAX) {
1845				PyErr_SetString(PyExc_OverflowError, "input too long");
1846				result = NULL;
1847			}
1848			else {
1849				result = PyString_FromStringAndSize(s, (int)(len-1));
1850			}
1851		}
1852		PyMem_FREE(s);
1853		return result;
1854	}
1855	if (v != NULL) {
1856		f = PySys_GetObject("stdout");
1857		if (f == NULL) {
1858			PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1859			return NULL;
1860		}
1861		if (Py_FlushLine() != 0 ||
1862		    PyFile_WriteObject(v, f, Py_PRINT_RAW) != 0)
1863			return NULL;
1864	}
1865	f = PySys_GetObject("stdin");
1866	if (f == NULL) {
1867		PyErr_SetString(PyExc_RuntimeError, "lost sys.stdin");
1868		return NULL;
1869	}
1870	return PyFile_GetLine(f, -1);
1871}
1872
1873static char raw_input_doc[] =
1874"raw_input([prompt]) -> string\n\
1875\n\
1876Read a string from standard input.  The trailing newline is stripped.\n\
1877If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1878On Unix, GNU readline is used if enabled.  The prompt string, if given,\n\
1879is printed without a trailing newline before reading.";
1880
1881
1882static PyObject *
1883builtin_reduce(self, args)
1884	PyObject *self;
1885	PyObject *args;
1886{
1887	PyObject *seq, *func, *result = NULL;
1888	PySequenceMethods *sqf;
1889	register int i;
1890
1891	if (!PyArg_ParseTuple(args, "OO|O:reduce", &func, &seq, &result))
1892		return NULL;
1893	if (result != NULL)
1894		Py_INCREF(result);
1895
1896	sqf = seq->ob_type->tp_as_sequence;
1897	if (sqf == NULL || sqf->sq_item == NULL) {
1898		PyErr_SetString(PyExc_TypeError,
1899		    "2nd argument to reduce() must be a sequence object");
1900		return NULL;
1901	}
1902
1903	if ((args = PyTuple_New(2)) == NULL)
1904		goto Fail;
1905
1906	for (i = 0; ; ++i) {
1907		PyObject *op2;
1908
1909		if (args->ob_refcnt > 1) {
1910			Py_DECREF(args);
1911			if ((args = PyTuple_New(2)) == NULL)
1912				goto Fail;
1913		}
1914
1915		if ((op2 = (*sqf->sq_item)(seq, i)) == NULL) {
1916			if (PyErr_ExceptionMatches(PyExc_IndexError)) {
1917				PyErr_Clear();
1918				break;
1919			}
1920			goto Fail;
1921		}
1922
1923		if (result == NULL)
1924			result = op2;
1925		else {
1926			PyTuple_SetItem(args, 0, result);
1927			PyTuple_SetItem(args, 1, op2);
1928			if ((result = PyEval_CallObject(func, args)) == NULL)
1929				goto Fail;
1930		}
1931	}
1932
1933	Py_DECREF(args);
1934
1935	if (result == NULL)
1936		PyErr_SetString(PyExc_TypeError,
1937			   "reduce of empty sequence with no initial value");
1938
1939	return result;
1940
1941Fail:
1942	Py_XDECREF(args);
1943	Py_XDECREF(result);
1944	return NULL;
1945}
1946
1947static char reduce_doc[] =
1948"reduce(function, sequence[, initial]) -> value\n\
1949\n\
1950Apply a function of two arguments cumulatively to the items of a sequence,\n\
1951from left to right, so as to reduce the sequence to a single value.\n\
1952For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1953((((1+2)+3)+4)+5).  If initial is present, it is placed before the items\n\
1954of the sequence in the calculation, and serves as a default when the\n\
1955sequence is empty.";
1956
1957
1958static PyObject *
1959builtin_reload(self, args)
1960	PyObject *self;
1961	PyObject *args;
1962{
1963	PyObject *v;
1964
1965	if (!PyArg_ParseTuple(args, "O:reload", &v))
1966		return NULL;
1967	return PyImport_ReloadModule(v);
1968}
1969
1970static char reload_doc[] =
1971"reload(module) -> module\n\
1972\n\
1973Reload the module.  The module must have been successfully imported before.";
1974
1975
1976static PyObject *
1977builtin_repr(self, args)
1978	PyObject *self;
1979	PyObject *args;
1980{
1981	PyObject *v;
1982
1983	if (!PyArg_ParseTuple(args, "O:repr", &v))
1984		return NULL;
1985	return PyObject_Repr(v);
1986}
1987
1988static char repr_doc[] =
1989"repr(object) -> string\n\
1990\n\
1991Return the canonical string representation of the object.\n\
1992For most object types, eval(repr(object)) == object.";
1993
1994
1995static PyObject *
1996builtin_round(self, args)
1997	PyObject *self;
1998	PyObject *args;
1999{
2000	double x;
2001	double f;
2002	int ndigits = 0;
2003	int i;
2004
2005	if (!PyArg_ParseTuple(args, "d|i:round", &x, &ndigits))
2006			return NULL;
2007	f = 1.0;
2008	i = abs(ndigits);
2009	while  (--i >= 0)
2010		f = f*10.0;
2011	if (ndigits < 0)
2012		x /= f;
2013	else
2014		x *= f;
2015	if (x >= 0.0)
2016		x = floor(x + 0.5);
2017	else
2018		x = ceil(x - 0.5);
2019	if (ndigits < 0)
2020		x *= f;
2021	else
2022		x /= f;
2023	return PyFloat_FromDouble(x);
2024}
2025
2026static char round_doc[] =
2027"round(number[, ndigits]) -> floating point number\n\
2028\n\
2029Round a number to a given precision in decimal digits (default 0 digits).\n\
2030This always returns a floating point number.  Precision may be negative.";
2031
2032
2033static PyObject *
2034builtin_str(self, args)
2035	PyObject *self;
2036	PyObject *args;
2037{
2038	PyObject *v;
2039
2040	if (!PyArg_ParseTuple(args, "O:str", &v))
2041		return NULL;
2042	return PyObject_Str(v);
2043}
2044
2045static char str_doc[] =
2046"str(object) -> string\n\
2047\n\
2048Return a nice string representation of the object.\n\
2049If the argument is a string, the return value is the same object.";
2050
2051
2052static PyObject *
2053builtin_tuple(self, args)
2054	PyObject *self;
2055	PyObject *args;
2056{
2057	PyObject *v;
2058
2059	if (!PyArg_ParseTuple(args, "O:tuple", &v))
2060		return NULL;
2061	return PySequence_Tuple(v);
2062}
2063
2064static char tuple_doc[] =
2065"tuple(sequence) -> list\n\
2066\n\
2067Return a tuple whose items are the same as those of the argument sequence.\n\
2068If the argument is a tuple, the return value is the same object.";
2069
2070
2071static PyObject *
2072builtin_type(self, args)
2073	PyObject *self;
2074	PyObject *args;
2075{
2076	PyObject *v;
2077
2078	if (!PyArg_ParseTuple(args, "O:type", &v))
2079		return NULL;
2080	v = (PyObject *)v->ob_type;
2081	Py_INCREF(v);
2082	return v;
2083}
2084
2085static char type_doc[] =
2086"type(object) -> type object\n\
2087\n\
2088Return the type of the object.";
2089
2090
2091static PyObject *
2092builtin_vars(self, args)
2093	PyObject *self;
2094	PyObject *args;
2095{
2096	PyObject *v = NULL;
2097	PyObject *d;
2098
2099	if (!PyArg_ParseTuple(args, "|O:vars", &v))
2100		return NULL;
2101	if (v == NULL) {
2102		d = PyEval_GetLocals();
2103		if (d == NULL) {
2104			if (!PyErr_Occurred())
2105				PyErr_SetString(PyExc_SystemError,
2106						"no locals!?");
2107		}
2108		else
2109			Py_INCREF(d);
2110	}
2111	else {
2112		d = PyObject_GetAttrString(v, "__dict__");
2113		if (d == NULL) {
2114			PyErr_SetString(PyExc_TypeError,
2115			    "vars() argument must have __dict__ attribute");
2116			return NULL;
2117		}
2118	}
2119	return d;
2120}
2121
2122static char vars_doc[] =
2123"vars([object]) -> dictionary\n\
2124\n\
2125Without arguments, equivalent to locals().\n\
2126With an argument, equivalent to object.__dict__.";
2127
2128static int
2129abstract_issubclass(derived, cls, err, first)
2130	PyObject *derived;
2131	PyObject *cls;
2132	char *err;
2133	int first;
2134{
2135	static PyObject *__bases__ = NULL;
2136	PyObject *bases;
2137	int i, n;
2138	int r = 0;
2139
2140	if (__bases__ == NULL) {
2141		__bases__ = PyString_FromString("__bases__");
2142		if (__bases__ == NULL)
2143			return -1;
2144	}
2145
2146	if (first) {
2147		bases = PyObject_GetAttr(cls, __bases__);
2148		if (bases == NULL || !PyTuple_Check(bases)) {
2149		        Py_XDECREF(bases);
2150	        	PyErr_SetString(PyExc_TypeError, err);
2151			return -1;
2152		}
2153		Py_DECREF(bases);
2154	}
2155
2156	if (derived == cls)
2157		return 1;
2158
2159	bases = PyObject_GetAttr(derived, __bases__);
2160	if (bases == NULL || !PyTuple_Check(bases)) {
2161	        Py_XDECREF(bases);
2162	        PyErr_SetString(PyExc_TypeError, err);
2163		return -1;
2164	}
2165
2166	n = PyTuple_GET_SIZE(bases);
2167	for (i = 0; i < n; i++) {
2168		r = abstract_issubclass(PyTuple_GET_ITEM(bases, i),
2169					cls, err, 0);
2170		if (r != 0)
2171			break;
2172	}
2173
2174	Py_DECREF(bases);
2175
2176	return r;
2177}
2178
2179static PyObject *
2180builtin_isinstance(self, args)
2181     PyObject *self;
2182     PyObject *args;
2183{
2184	PyObject *inst;
2185	PyObject *cls;
2186	PyObject *icls;
2187	static PyObject *__class__ = NULL;
2188	int retval = 0;
2189
2190	if (!PyArg_ParseTuple(args, "OO:isinstance", &inst, &cls))
2191		return NULL;
2192
2193        if (PyClass_Check(cls)) {
2194		if (PyInstance_Check(inst)) {
2195			PyObject *inclass =
2196				(PyObject*)((PyInstanceObject*)inst)->in_class;
2197			retval = PyClass_IsSubclass(inclass, cls);
2198		}
2199	}
2200	else if (PyType_Check(cls)) {
2201		retval = ((PyObject *)(inst->ob_type) == cls);
2202	}
2203	else if (!PyInstance_Check(inst)) {
2204	        if (__class__ == NULL) {
2205			__class__ = PyString_FromString("__class__");
2206			if (__class__ == NULL)
2207				return NULL;
2208		}
2209		icls = PyObject_GetAttr(inst, __class__);
2210		if (icls != NULL) {
2211			retval = abstract_issubclass(
2212				icls, cls,
2213				"second argument must be a class",
2214				1);
2215			Py_DECREF(icls);
2216			if (retval < 0)
2217				return NULL;
2218		}
2219		else {
2220			PyErr_SetString(PyExc_TypeError,
2221					"second argument must be a class");
2222			return NULL;
2223		}
2224	}
2225        else {
2226		PyErr_SetString(PyExc_TypeError,
2227				"second argument must be a class");
2228		return NULL;
2229	}
2230	return PyInt_FromLong(retval);
2231}
2232
2233static char isinstance_doc[] =
2234"isinstance(object, class-or-type) -> Boolean\n\
2235\n\
2236Return whether an object is an instance of a class or of a subclass thereof.\n\
2237With a type as second argument, return whether that is the object's type.";
2238
2239
2240static PyObject *
2241builtin_issubclass(self, args)
2242     PyObject *self;
2243     PyObject *args;
2244{
2245	PyObject *derived;
2246	PyObject *cls;
2247	int retval;
2248
2249	if (!PyArg_ParseTuple(args, "OO:issubclass", &derived, &cls))
2250		return NULL;
2251
2252	if (!PyClass_Check(derived) || !PyClass_Check(cls)) {
2253		retval = abstract_issubclass(
2254				derived, cls, "arguments must be classes", 1);
2255		if (retval < 0)
2256			return NULL;
2257	}
2258	else {
2259		/* shortcut */
2260	  	if (!(retval = (derived == cls)))
2261			retval = PyClass_IsSubclass(derived, cls);
2262	}
2263
2264	return PyInt_FromLong(retval);
2265}
2266
2267static char issubclass_doc[] =
2268"issubclass(C, B) -> Boolean\n\
2269\n\
2270Return whether class C is a subclass (i.e., a derived class) of class B.";
2271
2272
2273static PyMethodDef builtin_methods[] = {
2274	{"__import__",	builtin___import__, 1, import_doc},
2275	{"abs",		builtin_abs, 1, abs_doc},
2276	{"apply",	builtin_apply, 1, apply_doc},
2277	{"buffer",	builtin_buffer, 1, buffer_doc},
2278	{"callable",	builtin_callable, 1, callable_doc},
2279	{"chr",		builtin_chr, 1, chr_doc},
2280	{"cmp",		builtin_cmp, 1, cmp_doc},
2281	{"coerce",	builtin_coerce, 1, coerce_doc},
2282	{"compile",	builtin_compile, 1, compile_doc},
2283#ifndef WITHOUT_COMPLEX
2284	{"complex",	builtin_complex, 1, complex_doc},
2285#endif
2286	{"delattr",	builtin_delattr, 1, delattr_doc},
2287	{"dir",		builtin_dir, 1, dir_doc},
2288	{"divmod",	builtin_divmod, 1, divmod_doc},
2289	{"eval",	builtin_eval, 1, eval_doc},
2290	{"execfile",	builtin_execfile, 1, execfile_doc},
2291	{"filter",	builtin_filter, 1, filter_doc},
2292	{"float",	builtin_float, 1, float_doc},
2293	{"getattr",	builtin_getattr, 1, getattr_doc},
2294	{"globals",	builtin_globals, 1, globals_doc},
2295	{"hasattr",	builtin_hasattr, 1, hasattr_doc},
2296	{"hash",	builtin_hash, 1, hash_doc},
2297	{"hex",		builtin_hex, 1, hex_doc},
2298	{"id",		builtin_id, 1, id_doc},
2299	{"input",	builtin_input, 1, input_doc},
2300	{"intern",	builtin_intern, 1, intern_doc},
2301	{"int",		builtin_int, 1, int_doc},
2302	{"isinstance",  builtin_isinstance, 1, isinstance_doc},
2303	{"issubclass",  builtin_issubclass, 1, issubclass_doc},
2304	{"len",		builtin_len, 1, len_doc},
2305	{"list",	builtin_list, 1, list_doc},
2306	{"locals",	builtin_locals, 1, locals_doc},
2307	{"long",	builtin_long, 1, long_doc},
2308	{"map",		builtin_map, 1, map_doc},
2309	{"max",		builtin_max, 1, max_doc},
2310	{"min",		builtin_min, 1, min_doc},
2311	{"oct",		builtin_oct, 1, oct_doc},
2312	{"open",	builtin_open, 1, open_doc},
2313	{"ord",		builtin_ord, 1, ord_doc},
2314	{"pow",		builtin_pow, 1, pow_doc},
2315	{"range",	builtin_range, 1, range_doc},
2316	{"raw_input",	builtin_raw_input, 1, raw_input_doc},
2317	{"reduce",	builtin_reduce, 1, reduce_doc},
2318	{"reload",	builtin_reload, 1, reload_doc},
2319	{"repr",	builtin_repr, 1, repr_doc},
2320	{"round",	builtin_round, 1, round_doc},
2321	{"setattr",	builtin_setattr, 1, setattr_doc},
2322	{"slice",       builtin_slice, 1, slice_doc},
2323	{"str",		builtin_str, 1, str_doc},
2324	{"tuple",	builtin_tuple, 1, tuple_doc},
2325	{"type",	builtin_type, 1, type_doc},
2326	{"unicode",	builtin_unicode, 1, unicode_doc},
2327	{"unichr",	builtin_unichr, 1, unichr_doc},
2328	{"vars",	builtin_vars, 1, vars_doc},
2329	{"xrange",	builtin_xrange, 1, xrange_doc},
2330	{NULL,		NULL},
2331};
2332
2333static char builtin_doc[] =
2334"Built-in functions, exceptions, and other objects.\n\
2335\n\
2336Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.";
2337
2338PyObject *
2339_PyBuiltin_Init()
2340{
2341	PyObject *mod, *dict, *debug;
2342	mod = Py_InitModule4("__builtin__", builtin_methods,
2343			     builtin_doc, (PyObject *)NULL,
2344			     PYTHON_API_VERSION);
2345	if (mod == NULL)
2346		return NULL;
2347	dict = PyModule_GetDict(mod);
2348	if (PyDict_SetItemString(dict, "None", Py_None) < 0)
2349		return NULL;
2350	if (PyDict_SetItemString(dict, "Ellipsis", Py_Ellipsis) < 0)
2351		return NULL;
2352	debug = PyInt_FromLong(Py_OptimizeFlag == 0);
2353	if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2354		Py_XDECREF(debug);
2355		return NULL;
2356	}
2357	Py_XDECREF(debug);
2358
2359	return mod;
2360}
2361
2362/* Helper for filter(): filter a tuple through a function */
2363
2364static PyObject *
2365filtertuple(func, tuple)
2366	PyObject *func;
2367	PyObject *tuple;
2368{
2369	PyObject *result;
2370	register int i, j;
2371	int len = PyTuple_Size(tuple);
2372
2373	if (len == 0) {
2374		Py_INCREF(tuple);
2375		return tuple;
2376	}
2377
2378	if ((result = PyTuple_New(len)) == NULL)
2379		return NULL;
2380
2381	for (i = j = 0; i < len; ++i) {
2382		PyObject *item, *good;
2383		int ok;
2384
2385		if ((item = PyTuple_GetItem(tuple, i)) == NULL)
2386			goto Fail_1;
2387		if (func == Py_None) {
2388			Py_INCREF(item);
2389			good = item;
2390		}
2391		else {
2392			PyObject *arg = Py_BuildValue("(O)", item);
2393			if (arg == NULL)
2394				goto Fail_1;
2395			good = PyEval_CallObject(func, arg);
2396			Py_DECREF(arg);
2397			if (good == NULL)
2398				goto Fail_1;
2399		}
2400		ok = PyObject_IsTrue(good);
2401		Py_DECREF(good);
2402		if (ok) {
2403			Py_INCREF(item);
2404			if (PyTuple_SetItem(result, j++, item) < 0)
2405				goto Fail_1;
2406		}
2407	}
2408
2409	if (_PyTuple_Resize(&result, j, 0) < 0)
2410		return NULL;
2411
2412	return result;
2413
2414Fail_1:
2415	Py_DECREF(result);
2416	return NULL;
2417}
2418
2419
2420/* Helper for filter(): filter a string through a function */
2421
2422static PyObject *
2423filterstring(func, strobj)
2424	PyObject *func;
2425	PyObject *strobj;
2426{
2427	PyObject *result;
2428	register int i, j;
2429	int len = PyString_Size(strobj);
2430
2431	if (func == Py_None) {
2432		/* No character is ever false -- share input string */
2433		Py_INCREF(strobj);
2434		return strobj;
2435	}
2436	if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2437		return NULL;
2438
2439	for (i = j = 0; i < len; ++i) {
2440		PyObject *item, *arg, *good;
2441		int ok;
2442
2443		item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2444		if (item == NULL)
2445			goto Fail_1;
2446		arg = Py_BuildValue("(O)", item);
2447		Py_DECREF(item);
2448		if (arg == NULL)
2449			goto Fail_1;
2450		good = PyEval_CallObject(func, arg);
2451		Py_DECREF(arg);
2452		if (good == NULL)
2453			goto Fail_1;
2454		ok = PyObject_IsTrue(good);
2455		Py_DECREF(good);
2456		if (ok)
2457			PyString_AS_STRING((PyStringObject *)result)[j++] =
2458				PyString_AS_STRING((PyStringObject *)item)[0];
2459	}
2460
2461	if (j < len && _PyString_Resize(&result, j) < 0)
2462		return NULL;
2463
2464	return result;
2465
2466Fail_1:
2467	Py_DECREF(result);
2468	return NULL;
2469}
2470